如何验证提交的 ActiveRecord 的单个属性而不是其所有属性?

发布于 2024-10-24 22:32:30 字数 409 浏览 1 评论 0原文

我正在使用 Ruby on Rails 3,我想验证提交的 ActiveRecord 的单个属性而不是其所有属性。

例如,在我的模型中:

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

我想分别对 :firstname:lastname 运行验证。 可能吗?如果是这样,我该怎么做?


PS:我知道出于验证目的,有“validates_presence_of”、“validates_confirmation_of”等方法,...,但我只想使用上面的代码。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

傻比既视感 2024-10-31 22:32:30

您可以在模型上设置虚拟属性,然后根据该属性进行条件验证。

您可以在 http://railscasts.com/episodes/41-conditional-validations 找到有关此内容的截屏视频

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

暮倦 2024-10-31 22:32:30
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
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
思念绕指尖 2024-10-31 22:32:30

您可以删除上面代码的第二行,这样它就显示为:

validates :firstname, :presence => true

不会对 :lastname 执行任何验证。

问候

罗宾

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文