Rails-仅当另一个字段具有特定值时,才如何验证一个字段? [英] Rails - How to validate a field only if a another field has a certain value?
问题描述
我对Rails还是很陌生,现在遇到了一个无法与我的朋友Google解决的问题:)
I'm pretty new to Rails and I now came across a problem which I wasn't able to solve with my friend Google :)
在我的表单中,我有一个带有三个值的Select:苹果,香蕉和樱桃.如果让我选择的苹果从选择我躲在另一个选择 - 和文本场与一些JavaScript,因为当苹果选择,没有必要填补这些其他两个字段了.
In my form I have a Select with three values: Apple, Banana and Cherry. If I choose Apple from the select I hide another Select- and a Text-field with some Javascript, because when Apple is chosen, there is no need to fill in these other two fields anymore.
所以现在我在提交表单时验证表单时遇到了问题. 我发现了一些类似的问题,例如 仅当另一个字段为空白时才验证该字段."
So now I have a problem with validating my form when it's submitted. I've found some similar problems for example in the case of "Only validate a field if another is blank."
此问题的解决方法如下:
This Problem was solved like this:
validates_presence_of :mobile_number, :unless => :home_phone?
所以我刚刚尝试了想到的第一件事:
So I've just tried the first thing which popped into my mind:
validates_presence_of :state, :granted_at, :if => :type != 1
但是当我运行它时,出现此错误:
But when I run it, I get this error:
undefined method `validate' for true:TrueClass
所以现在我不知道如何从已创建的对象访问值... 在此先感谢您的帮助,我希望我的问题不会像听起来那样明显:-)
So now I didn't find out how I can access values from the object which was created... Thank you in Advance for your help and I hope my question isn't as obvious as it sounds :-)
推荐答案
由于它是可执行代码,因此需要将其包装在lambda或Proc对象中,如下所示:
Because it is executable code you need to wrap it in a lambda or a Proc object like so:
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 }
这篇关于Rails-仅当另一个字段具有特定值时,才如何验证一个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!