validate(*args, &block) public

Adds a validation method or block to the class. This is useful when overriding the validate instance method becomes too unwieldy and you’re looking for more descriptive declaration of your validations.

This can be done with a symbol pointing to a method:

class Comment
  include ActiveModel::Validations

  validate :must_be_friends

  def must_be_friends
    errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
  end
end

With a block which is passed with the current record to be validated:

class Comment
  include ActiveModel::Validations

  validate do |comment|
    comment.must_be_friends
  end

  def must_be_friends
    errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
  end
end

Or with a block where self points to the current record to be validated:

class Comment
  include ActiveModel::Validations

  validate do
    errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
  end
end
Show source
Register or log in to add new notes.
June 28, 2011
0 thanks

Typo in example above

You aren’t mistaken. That is an error in the example with the block above. There’s an extra ‘(’ character.

May 28, 2012
0 thanks

Accepted parameters for validate

Validate method also accepts :on and :if parameters. The default value for :on is :save, the other accepted values are :create and :update

class Comment
  include ActiveModel::Validations

  validate :must_be_friends, :on => :create, :if => Proc.new {|comment| some_condition}

  def must_be_friends
    errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
  end
end