我通常不使用表格来表单,但是当使用嵌套表单时(使用nested_form或cocoon gem时),将每组表单元素放在表格行中是否可以?
对我来说,这看起来非常直观:表中的每一行都代表一个对象。但是默认情况下,nested_form和cocoon gem都没有在它们的示例中添加表格,所以我想知道使用表单是不是最好的方法?
答案 0 :(得分:25)
是。如果要输入表格数据,则应使用表格。
我还没有测试过以下示例,但我认为它应该可行。假设您正在构建包含大量订单项的收据,每个订单项都包含说明和价格。在你看来做:
%table
%thead
%tr
%th Description
%th Price
%tbody.line_items
= f.simple_fields_for :line_items do |f|
= render 'line_item_fields', f: f
.links
= link_to_add_association "Add", f, :line_items, data: {"association-insertion-node" => "tbody.line_items", "association-insertion-method" => "append"}
association-insertion-node :它控制插入新line_item的位置。在示例中,我使用表体。
association-insertion-method :用于插入新line_item的jQuery方法。在示例中,我将它附加到表体的末尾。
在_line_item_fields.html.haml中:
%tr.nested-fields
%td= f.input :description, label: false
%td= f.input :price, label: false
%td= link_to_remove_association "Remove"
.nested-fields 类非常重要,因为它告诉cocoon当"删除"单击链接。