Rails – 如果另一个字段具有特定值,如何validation字段?

我是Rails的新手,我现在遇到了一个我无法用我的朋友谷歌解决的问题:)

在我的表格中,我有一个具有三个值的选择: AppleBananaCherry 。 如果我从选择中选择Apple ,我会隐藏另一个Select-和带有一些Javascript的文本字段,因为当选择Apple时,不再需要填写其他两个字段。

所以现在我在提交表单时validation表单时遇到问题。 我发现了一些类似的问题,例如“如果另一个是空白则仅validation字段”。

这个问题解决了这样:

validates_presence_of :mobile_number, :unless => :home_phone? 

所以我刚刚尝试了第一件突然出现的事情:

 validates_presence_of :state, :granted_at, :if => :type != 1 

但是当我运行它时,我收到此错误:

 undefined method `validate' for true:TrueClass 

所以现在我没有找到如何从创建的对象中访问值…感谢您提前获得的帮助,我希望我的问题不像听起来那么明显:-)

因为它是可执行代码,所以需要将它包装在lambda或Proc对象中,如下所示:

 validates_presence_of :state, :granted_at, :if => lambda { |o| o.type != 1 } # alternatively: ..., :if => lambda { self.type != 1 } ..., :if => Proc.new { |o| o.type != 1 } ..., :if ->(o) { o.type != 1 } 

你可以使用if flag和lambda:

 validates_presence_of :state, :granted_at, :if => lambda {self.type != 1} 

或者只是创建私有方法:

 validates_presence_of :state, :granted_at, :if => :valid_type? private def valid_type? type != 1 end 

虽然上面提到的方法是最佳实践,但你也可以这样简单:

 validates_presence_of :state, :granted_at, :if => "type!=1" 

在前面的答案的基础上,您还可以使用更短的“箭头”语法

 validates :state, :granted_at, presence: true, if: ->(o) { o.type != 1 }