开发者

How to validate a single attribute for a submitting ActiveRecord instead of all its attributes?

开发者 https://www.devze.com 2023-02-18 03:08 出处:网络
I am using Ruby on Rails 3 and I would like to validate a single attribute for a submitting ActiveRecord instead of all its attributes.

I am using Ruby on Rails 3 and I would like to validate a single attribute for a submitting ActiveRecord instead of all its attributes.

For example, in my model I have:

validates :firstname, :presence => true, ...
validates :lastname,  :presence => true, ...

I would like to run validation on the :firstname and on the :lastname separately. Is it possible? If so, how can I make that?


P.S.: I k开发者_开发百科now that for validation purposes there are methods like "validates_presence_of", "validates_confirmation_of", ..., but I would like to use only the above code.


You can setup a virtual attribute on your model, and then do conditional validation depending on that attribute.

You can find a screencast about this at http://railscasts.com/episodes/41-conditional-validations


class Model < ActiveRecord::Base  
  def save(*attrs)
    Model.validates :firstname, :presence => true if attrs.empty? || attrs.include?( :firstname )
    Model.validates :lastname,  :presence => true if attrs.empty? || attrs.include?( :lastname )
    ...
    super
  end
end

m = Model.new
m.save
#=> false
m.save(nil) # same as save(false), you can use both of them
#=> true
m = Model.new :firstname => "Putty"
m.save
#=> false
m.save(:firstname, :lastname)
#=> false
m.save(:firstname)
#=> true


You can just delete the second line of your code above so it reads:

validates :firstname, :presence => true

No validation will then be performed on the :lastname.

Regards

Robin

0

精彩评论

暂无评论...
验证码 换一张
取 消