Validation on create with Ripple (Riak On Rails)

Previously I mentioned how to achieve Uniqueness Validation With Ripple.

Similarly, Ripple doesn’t provide direct method for adding validation only on create while trying to implement Riak On Rails using Ripple as modeling layer. This is very much necessary for the validation of properties such as password which are to be checked only while being created. Below is the code sample I developed for validation on create manually.

class User
  include Ripple::Document
  attr_accessor :password
  validates :password, :presence => true, :length => { :in => 8..20 }, :if => :not_created?
  def not_created?

After searching for a while and trying to think of a way, I realized that the key for the object is only determined after it is saved or created. Also, I noticed that Ripple, (Riak On Rails) does support if in the validates class method. Hence, the method in the above code block i.e. “not_created?” checks for the presence of key and the validation is only performed if key is not present resulting the validation to be checked only when the object is created.

This technique may also work in other Rails application where key is replaced by id. The scenario to use this method would be when “:on => :create” doesn’t work or is not supported.

If you have any questions or suggestions please feel free to comment as I’m always ready to learn… 🙂