Rails nested attribute arrays

I am having trouble creating multiple model objects using nested attributes. .Erb form I have:

<%= f.fields_for :comments do |c| %> <%= c.text_field :text %> <% end %> 

generates input fields that look like this:

 <input type="text" name="ad[comments_attributes][0][text]" /> <input type="text" name="ad[comments_attributes][1][text]" /> <input type="text" name="ad[comments_attributes][2][text]" /> 

when I really want it to look like this:

 <input type="text" name="ad[comments_attributes][][text]" /> <input type="text" name="ad[comments_attributes][][text]" /> <input type="text" name="ad[comments_attributes][][text]" /> 

Using form helpers, how can I create a form that creates an array of hashes, as in the second example, instead of the hash of the hashes, how does this happen in the first?

+4
source share
1 answer

You can use text_field_tag ​​for this particular type. This FormTagHelper provides a number of methods for creating form tags that do not rely on an Active Record object assigned to a template, such as FormHelper. Instead, you specify names and values ​​manually.

If you give them all the same name and add [] to the end as follows:

  <%= text_field_tag "ad[comments_attributes][][text]" %> <%= text_field_tag "ad[comments_attributes][][text]" %> <%= text_field_tag "ad[comments_attributes][][text]" %> 

You can access them from the controller:

comments_attributes = params [: ad] [: comments_attributes] # this is an Array

The above output of field_tag ​​html is as follows:

 <input type="text" name="ad[comments_attributes][][text]" /> <input type="text" name="ad[comments_attributes][][text]" /> <input type="text" name="ad[comments_attributes][][text]" /> 

If you enter values ​​between square brackets, the rails will treat it as a hash:

  <%= text_field_tag "ad[comments_attributes][1][text]" %> <%= text_field_tag "ad[comments_attributes][2][text]" %> <%= text_field_tag "ad[comments_attributes][3][text]" %> 

will be interpreted by the controller as a hash with the keys "1", "2" and "3". I hope I understand correctly what you need.

thanks

+7
source

Source: https://habr.com/ru/post/1484879/


All Articles