简体   繁体   English

Rails中的条件验证

[英]Conditional validation in Rails

I have a model. 我有一个模特。 In some cases I need to validate all its fields for presence and another kinds of stuff, in other cases I need to validate only some of them and other fields can remain empty. 在某些情况下,我需要验证其所有字段的存在性和其他种类的东西,在其他情况下,我只需要验证其中的一些字段,而其他字段可以保留为空。 What's the best way to achieve this? 实现此目标的最佳方法是什么?

Check this 检查一下

validates_presence_of :state, :if => :in_us?

def in_us?
  country == 'US'
end

Here it validates presence of state only if country is US. 在这里,仅当国家是美国时,它才验证州的存在。 For other country id dosen't validates state. 对于其他国家/地区,id不会验证状态。

For detail: http://railscasts.com/episodes/41-conditional-validations 有关详细信息: http : //railscasts.com/episodes/41-conditional-validations

您可以使用条件验证。请参考文档http://guides.rubyonrails.org/active_record_validations.html#5.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM