Uniqueness Validation With Ripple (Riak On Rails)

I’m a riak newbie who is trying to implement Riak On Rails using Ripple as modeling layer. But while creating User model, I wanted validation for uniqueness of user. Validation such as presence is available with Ripple but I couldn’t find proper validation method directly provided for the uniqueness. So, below is the sample code of User model I developed for validation.

class User
  include Ripple::Document

  VALID_EMAIL_REGEX = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
  
  property :email, String, :presence => true, format: {  with: VALID_EMAIL_REGEX }, :index => true

  validate :unique_email_address?

  private

  def unique_email_address?
    errors.add(:email, 'The email is already taken.') if User.find_by_index('email', "#{self.email}").any?
  end
  
end

This is simple but it was actually difficult to find the available methods in Ripple. In the code above “index: true” enables the property to be indexed automatically. Which later gives us the ability to use “find_by_index” to use the “Secondary Indexes In Riak“.

This should do the trick but you may face some problem while trying to implement the Secondary Indexes with find_by_index. Configuring the Secondary Indexes in the Riak-Server you’re using should fix the problem.

The problem I was facing with Riak-server was that backend being used was “bitcask” whereas secondary indexes (2i) is supported by LevelDB or Memory backend (or one of those in conjunction with the Multi backend).

This can simply be changed by modifying the values in your app.config file.

The task is not yet complete since, the validation is checked every time the save is called. So, it’s not letting us to change other values and save. I’m trying to find the solution for that. Will update this post on success. If you have any suggestions please feel free to comment as I’m always ready to learn… 🙂


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *