我在尝试将支架与两个常驻&复选框链接时遇到问题。如果选择了多个展台,它们似乎是分开存放的。
如果我有一个支架,参数似乎以正确的方式存储在一个数组的哈希中,但是一旦我将另一个支架添加到同一个数组,它似乎交换了哈希。我的视图是这样的。你还有另一个选择,可以添加另一个调用相同部分的支架:
- unless @stands.empty? %tr#show_stands.contentText %td{:width => "27%", :valign => "top"} Select Stand For Ownership %td{:width => "15%", :valign => "top"} = collection_select "owned_stands[]", "stand_id", @stands, :id, :erf_no_rr_no, options ={:prompt =>"Please select stand..."}, {:class => 'dropdownSelect'} %td{:valign => "top"} = check_box_tag "owned_stands[][owner_comm_list]" Add to Owners Communication list = check_box_tag "owned_stands[][resident_comm_list]" Add to Residents Communication list
我期待一个包含两个哈希或更多哈希的数组,具体取决于我选择的支架数量。如果我选择了一个支架和两个复选框,我希望哈希谎言:
([{"stand_id" => "1", "resident_comm_list" => "1", "owner_comm_list" => "1"}])
如果我有两个,我期待:
([{"stand_id" => "1", "resident_comm_list" => "1", "owner_comm_list" => "1"},{"stand_id" => "2", "resident_comm_list" => "1", "owner_comm_list" => "1"}])
但现在,如果我选择两个看台,我会发现:
([{"stand_id" => "1", "resident_comm_list" => "1"}, {"owner_comm_list" => "1"},{"stand_id" => "2"},{"resident_comm_list" => "1", "owner_comm_list" => "1"}])
当我必须遍历哈希以选择stand_id时,它会在我的控制器中给出错误。
答案 0 :(得分:2)
问题在于你的check_box_tags没有正确定义它们应该适合的params散列中的位置。
Rails通常可以轻松实现所有嵌套,而无需您使用硬编码字段ID。不幸的是,当您尝试使用一系列复选框时,这些便捷方法会失败。由于checkbox gotcha涉及默认值和数组。
您对check_box_tag的使用避免了问题,但要求您填写表单对象通常提供的信息。
在我看来,来自多个部分的所有字段都被添加到同一个params数组中。 Rails处理数组中的重复参数的方法是启动另一个索引。
仔细研究所产生的来源,作为获得正确结果的线索。
您发布的代码需要付出太多努力才能达到我可以使用它的程度。所以我不能保证这会起作用。也没有发布控制器代码,没有办法说出它为什么会抛出错误。
无论您想要为每个部分的params添加索引,都要使用该解决方案。
你想做这样的事情。其中index是每个partial的唯一值。
- unless @stands.empty?
%tr#show_stands.contentText
%td{:width => "27%", :valign => "top"}
Select Stand For Ownership
%td{:width => "15%", :valign => "top"}
= collection_select "owned_stands[#{index}][]", "stand_id", @stands, :id, :erf_no_rr_no, options ={:prompt =>"Please select stand..."}, {:class => 'dropdownSelect'}
%td{:valign => "top"}
= check_box_tag "owned_stands[#{index}][owner_comm_list]"
Add to Owners Communication list
= check_box_tag "owned_stands[#{index}][resident_comm_list]"
Add to Residents Communication list
它会产生这样的参数哈希: 对于一个包含两个复选框的展台:
params["owned_stands"] =
{"0" =>
{"stand_id" => 1, "owner_comm_list" => 1, "resident_comm_list" => 1}
}
对于包含两个复选框的两个展位:
prams[owned_stands] =
{
"0" =>
{"stand_id" => 1, "owner_comm_list" => 1, "resident_comm_list" => 1},
"1" =>
{"stand_id" => 2, "owner_comm_list" => 1, "resident_comm_list" => 1}
}
您可能希望查看accepts_nested_attributes_for和嵌套fields_for用法。它们在视图和控制器中简化了这种事情,但仍然成为复选框的牺牲品。