在我的模型中,我有以下内容:
attr_accessor :address, :located_in_us
validates_length_of :address, :in => 1..50, :message => "Required field, please enter your address."
在我的表格上,我有一个单选按钮,询问他们是否位于美国。如果他们选择“是”,那么我想要地址字段。当他们点击“否”时,我有一个显示/隐藏隐藏包含地址的DIV,但表单永远不会提交,因为该字段,即使它是隐藏的,它仍然是必需的。
我尝试了以下内容:
validates_length_of :address, :in => 1..50, :message => "Required field, please enter your address.", :unless => :located_in_us == "1"
但它似乎不起作用,因为地址下方添加的javascript如下所示:
<script type='text/javascript'>$(function() { $('[name="myform[address]"]').rules('add', {"maxlength":50,"required":true,"unless":false,"minlength":1,"messages":{"required":"Required field, please enter your address."}});});</script>
我的问题是......如何制作表单,以便当用户点击“否”单选按钮(他们不在美国)时,地址字段不再是必填字段?
答案 0 :(得分:0)
我认为模型验证的:unless
选项应该是lambda
或Proc
:
validates_length_of :address, :in => 1..50, :message => "Required field, please enter your address.", :unless => lambda { |o| o.located_in_us == "1" }
我不确定你的内容是如何被解释的,但我猜是因为:unless
值的评估结果是false
,就好像它不存在一样。
对于客户端jQuery规则,我认为unless
选项不存在。适当的选项是depends
:
$(function() {
$('[name="myform[address]"]').rules('add',
{ "maxlength":50,
"required": {
"depends": function(){
return $("input:radio[name=located_in_us]:checked").val() != "1"; // I think this should get the value of the radio button, but double check...
}
},
"messages": {"required":"Required field, please enter your address."}
});
});