如何将nested_form_fields与分组记录一起使用?

时间:2015-04-24 09:53:49

标签: ruby-on-rails ruby-on-rails-4 nested-forms activeview

默认情况下,nested_form_fields gem会在<% = f.nested_fields_for %>标记下呈现指定关联jsut的所有现有记录。

问题是如何将nested_form_fields与名称(MyModel.all.group_by(&:name))的模型分组相结合,以便每个组将显示仅属于该特定组的记录

-@product_categories.each do |category|
  %h3= category.name
  =f.add_nested_fields_link :products, 'Add Product'
  -category.products.each do |product|
    = f.nested_fields_for :products, product, legend: 'Product' do |product_form|
      = product_form.text_field :name

1 个答案:

答案 0 :(得分:0)

无需在内循环中循环遍历这些产品。如果一个类别有很多产品你可以做

- @product_categories.each do |category|
  %h3= category.name
  = form_for category do |f|
    = f.add_nested_fields_link :products, 'Add Product'
    = f.nested_fields_for :products, legend: 'Product' do |product_form|
      = product_form.text_field :name

编辑:如果您只想要一个表单,则可以使用具有多个类别的更高级别对象,例如:

= form_for @object_with_categories do |f|
  = f.fields_for :categories do |f_cat|
    %h3= f_cat.object.name
    = f_cat.add_nested_fields_link :products, 'Add Product'
    = f_cat.nested_fields_for :products, legend: 'Product' do |product_form|
       = product_form.text_field :name