带有以下复选框标记:
<%= check_box_tag 'object[boolean_attribute]', 1, object.boolean_attribute %>
我只能在一个方向上更新boolean_属性:从false到true.
When is unchecked by default (because object.boolean_attribute is false) and I check it and then submit the form, a :boolean_attribute => 1 parameter is posted.
But,当我try 从true更新为false时,没有传递任何参数,因此布尔值_属性仍然为true.
In other words, when is checked by default (because object.boolean_attribute is true) and I uncheck it and then submit the form, a :boolean_attribute => 0 is not posted.
How can I make this check_box_tag to post a :boolean_attribute => 0 parameter when unchecked?
从api中,我不知道是否有一些选项可以轻松实现:
非常感谢.
EDIT
由于某些原因,我无法理解,在我的实际代码(带有嵌套的多对多关联)中,隐藏的_字段_标记不起作用.
<%= hidden_field_tag 'order[preparations_attributes][][cooked]', nil %>
<%= check_box_tag 'order[preparations_attributes][][cooked]', '1', preparation.cooked? %>
现在我遇到了相反的问题:我可以取消选中复选框,准备工作将更新为aspected,但如果我选中复选框,它会弄乱参数.
以下是未选中框的已发布参数:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"bGgPGbk+Cuk2q+LEgqetmk4e7xie8dB3iMP9Cj3SUm0=", "order"=>{"customer_name"=>"Duccio Armenise", "duedate"=>"2012-04-25 09:24:00.000000", "preparations_attributes"=>[{"quantity"=>"1", "description"=>"custom recipe", "kind"=>"custom", "cooked"=>"", "recipe_id"=>"9", "id"=>"86", "quantities_attributes"=>[{"ingredient_id"=>"", "qty"=>"", "_destroy"=>"0"}, {"ingredient_id"=>"11", "qty"=>"5.0", "id"=>"193", "_destroy"=>"0"}], "_destroy"=>"0"}], "add_preparation"=>{"recipe_id"=>""}}, "continue"=>"Confirm", "id"=>"31"}
Now see what a mess when I check the checkbox, beginning from "cooked"=>" ", for some reason Rails is closing the preparation_attributes hash too early!
Parameters: {"utf8"=>"✓", "authenticity_token"=>"bGgPGbk+Cuk2q+LEgqetmk4e7xie8dB3iMP9Cj3SUm0=", "order"=>{"customer_name"=>"Duccio Armenise", "duedate"=>"2012-04-25 09:24:00.000000", "preparations_attributes"=>[{"quantity"=>"1", "description"=>"custom recipe", "kind"=>"custom", "cooked"=>""}, {"cooked"=>"1", "recipe_id"=>"9", "id"=>"86", "quantities_attributes"=>[{"ingredient_id"=>"", "qty"=>"", "_destroy"=>"0"}, {"ingredient_id"=>"11", "qty"=>"5.0", "id"=>"193", "_destroy"=>"0"}], "_destroy"=>"0"}], "add_preparation"=>{"recipe_id"=>""}}, "continue"=>"Confirm", "id"=>"31"}
EDIT #2:
我想我遇到了一个Rails bug,它与深度嵌套的资源表单和参数传递有关:https://github.com/rails/rails/issues/5937
目前,我使用了一个select_标签:
<%= select_tag 'order[preparations_attributes][][cooked]', options_for_select({yes: 1, no: 0}, preparation.cooked? ? 1 : 0) %>
我认为切换到select_标签以避免"hidden_field gotcha"是一种可以接受的解决方法.
不管怎样,谢谢你的回答!