Ruby on Rails Active Record Notes 4 Validations
Build-in
:message example :message=>’too long’
: on example : on=>:create
validates :title, :presence => true
validates :email, :uniqueness => true, :length => { :within => 5..50 }
// other :length options //
:minimum
:maximum
:is
:within
:allow_nil
:too_long
:too_short
:wrong_length
:message
Format of an attribute (regex)
:format => { :with => /^[^@][\w.-][+@][\w.-]+[.][a-z]{2,4}$/i }
validates :password, :confirmation => true
other validations
:numbericality
:inclusion
:exclusion
:acceptance
custom error validation (example for model, add to errors Object)
def article_should_be_published
errors.add(:article_id, “is not published yet”) if article && !article.published?
end
this custom method is invoked prior to save via the validate method, different from validates, full model class example:
class Comment < ActiveRecord::Base
attr_accessible :article_id, :body, :email, :name
belongs_to :article
validates :name, :email, :body, :presence => true
validate :article_should_be_published
def article_should_be_published
errors.add(:article_id, “is not published yet”) if article && !article.published?
end
end