Grouping and fields_for

I am trying to create a form that allows me to submit new entries for an association in which association entries are combined.

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

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

Below fields_forgives me the correct entries with names such as product[properties_attributes][0][value].

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

But as soon as I try to 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

Create inputs for which the attribute name, for example product[product_property][value], when it should be product[property_attributes][0][value]in accordance with the first example.

In the Rails documentation, you can do the following:

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

But this gives the error "undefined method value for the array".

+5
source share
2 answers

:

- @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

, accepts_nested_attributes_for :properties rails, , properties_attributes. , attr_accessible :properties_attributes, Rails, ;)

, , :

- @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

: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for One-To-Many

+6

Rails , . , - , .

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

  def group_names
    properties.map(&:group_name).uniq.sort
  end
end

- for group_name in product.group_names
  = form.fields_for :properties do |pform|
    %h3= group_name
    - if pform.object.group_name.eql?(group_name)
      = pform.input :value

, . has_many: properties - % h3, .

- previous_group_name = nil
= form.fields_for :properties do |pform|
  - if pform.object.group_name != previous_group_name
    %h3= pform.object.group_name
  = pform.input :value
  - previous_group_name = pform.object.group_name

...

+1

All Articles