我正在使用 cocoon 添加嵌套属性。我认为有以下代码:
<table>
<thead>
<tr>
<th>Title</th>
<th>Action</th>
</tr>
</thead>
<tbody id="emergency_personnels">
<%= f.fields_for :emergency_personnels do |emergency_personnel| %>
<%= render 'emergency_personnel_fields', f: emergency_personnel %>
<% end %>
</tbody>
</table>
<%= link_to_add_association 'Add emergency personnel', f, :emergency_personnels, data: {"association-insertion-node" => "tbody#emergency_personnels", "association-insertion-method" => "append"} %>
它应该可以正常工作,但新字段不会附加在表的主体下,而是显示在表之外。
任何人都可以提出解决方案吗?谢谢
最佳答案
根据 cocoon 文档: insertion-behaviour
默认行为:
The default insertion location is at the back of the current container.
如果您想添加到自定义位置,那么我们可以通过两个数据属性来实现:
association-insertion-method
添加位置
association-insertion-node
将其添加到与节点相关的位置
示例如下:
$(document).ready(function() {
$("#owner a.add_fields").
data("association-insertion-method", 'append').
data("association-insertion-node", '#parent_table');
});
注意:
如果您想将模板添加到特定位置,即:
- 不是链接的直接父级或同级
- 链接出现多次 - 例如,在深度嵌套的表单内
您需要将 association-insertion-node
指定为函数。例如
$(document).ready(function() {
$(".add_sub_task a").
data("association-insertion-method", 'append').
data("association-insertion-node", function(link){
return link.closest('.row').next('.row').find('.sub_tasks_form')
});
});
关于ruby-on-rails - 无法使用 cocoon 追加表中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38907229/