0

在我的模型中,我有以下内容:

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>

我的问题是......我如何制作表格,以便当用户单击“否”单选按钮(他们不住在美国)时,地址字段不再是必填字段?

4

1 回答 1

0

我认为您:unless的模型验证选项应该是 alambda或 a 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."}
                 });
});
于 2012-04-19T21:23:20.207 回答