Search code examples
ruby-on-rails-3fields-for

grouping and fields_for


I'm trying to create a form which allows me to submit new records for an association where the association inputs are grouped.

   class Product < AR::Base
     has_many :properties
     accepts_nested_attributes_for :properties
   end

Note that in the controller a series of properties are built for the product, so @product.properties.empty? # => false.

The below fields_for gives me the correct inputs with names such as product[properties_attributes][0][value].

= form.fields_for :properties do |pform|                                                                                                                               
  = pform.input :value

But as soon as I try and group the association it no longer generates inputs with the correct names:

- @product.properties.group_by(&:group_name).each do |group_name, properties|
  %h3= group_name                                                       
  = form.fields_for properties do |pform|                                                                                                                               
    = pform.input :value

This create inputs which the name attribute like product[product_property][value] when in fact it should be product[property_attributes][0][value] as per the first example.

The Rails documentation suggests you can do this:

= form.fields_for :properties_attributes, properties do |pform|

But this gives an error "undefined method value for Array".


Solution

  • You need to set up like this:

    - @product.properties.group_by(&:group_name).each do |group_name, properties|
      %h3= group_name
      = form.fields_for :properties, properties do |pform|
        = pform.text_field :value
    

    It should work fine, since you have accepts_nested_attributes_for :properties rails know that it's supposed to create fields for properties_attributes. Moreover you may want to add attr_accessible :properties_attributes if you are using one of newest Rails and if you didn't add it to your model yet ;)

    Also, if you want to make some decision base on single property you may use the following form as well:

    - @product.properties.group_by(&:group_name).each do |group_name, properties|
      %h3= group_name
      - properties.each do |property|
        = form.fields_for :properties, property do |pform|
          = pform.text_field :value
    

    Both of them are nicely described here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for under One-To-Many section