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

本小妞迷上赌 提交于 2020-02-05 04:33:15

问题


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 know that for validation purposes there are methods like "validates_presence_of", "validates_confirmation_of", ..., but I would like to use only the above code.


回答1:


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




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/5367508/how-to-validate-a-single-attribute-for-a-submitting-activerecord-instead-of-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!