我使用Rails来自动地创建基于一组复杂的嵌套属性的子对象。因此,我需要以非常特殊的方式嵌套参数。显然,我意识到我可以使用JS来构建它们,但是我希望表单的顺序自动地帮助构建。对于上下文,我有2列,由2 td表示。每列可以创建新记录或编辑现有记录。当然,当现有记录被修改时,记录的id必须被传递。
呈现的HTML如下:
<td width="50%" style="padding-right:3%" class="logistic-details" data-type="logistics" data-typelogistics="delivery" data-instructions="test instructions" data-id="1" data-amount="20"> <span class="area-to-inject-amount-inputs" data-object="type_logistics" data-type="logistics" data-typelogistics="delivery"> <input class="labeler-response" name="type_logistics_attributes[][id]" type="hidden" value="1"> <input class="labeler-response" name="type_logistics_attributes[][instructions]" type="text" value="test instructions"> </span> </td> <td width="50%" style="padding-right:3%" class="logistic-details" data-type="logistics" data-typelogistics="pickup" data-instructions="" data-id="" data-amount="0"> <span class="area-to-inject-amount-inputs" data-object="type_logistics" data-type="logistics" data-typelogistics="pickup" data-actioned="charged"> <input type="hidden" name="type_logistics_attributes[][type_of_logistics]" value="pickup"> <input class="injected-amount-input" type="number" min="0" max="" placeholder="Amount" name="type_logistics_attributes[][charged_amounts_attributes][][amount]" value="20"> <span class="area-to-inject-type-of-amount"> <input type="hidden" name="type_logistics_attributes[][charged_amounts_attributes][][type_of_amount]" value="logistics"> </span> <input class="labeler-response" name="type_logistics_attributes[][instructions]" type="text" placeholder="Enter address and instructions"> </span> </td>
在这种情况下,第一< td>正在修改ID为1的现有记录,而第二个< td>提供了创建新记录的参数。创建新记录时,还会创建child charged_amounts。因此,这些是我期望的参数:
"type_logistics_attributes"=>[ {"id"=>"1","instructions"=>"test instructions"},{"type_of_logistics"=>"pickup","charged_amounts_attributes"=>[{"amount"=>"40","type_of_amount"=>"logistics"}],"instructions" => "123 Fake street"} ]
相反,我得到如下:
"type_logistics_attributes"=>[ {"id"=>"1","type_of_logistics"=>"pickup","instructions"=>"test instructions","type_of_amount"=>"logistics"}]},{"instructions"=>"123 Fake street"} ]
不知何故,< td>边界不起作用,并且child charged_amount属性以某种方式被集中到第一个< td>现有记录修改。
谢谢!
解决方法
它不是< td>或任何类似的HTML元素,作为输入的“边界”,仅为
<form>
element。在< form>内的所有输入标签在提交表单时由浏览器作为参数发送。您可能在一个< form>中有两列这就是为什么两个列的参数混合在参数中。