I am having trouble creating multiple model objects using nested attributes. The form .erb I have:
<%= f.fields_for :comments do |c| %>
<%= c.text_field :text %>
<% end %>
is generating 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 what I really want is for 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 make the form create an array of hashes like I have in the second example, instead of a hash of hashes as it does in the first?
You could use text_field_tag for this particular type requirement. This FormTagHelper provides a number of methods for creating form tags that doesn’t rely on an Active Record object assigned to the template like FormHelper does. Instead, you provide the names and values manually.
If you give them all the same name and append [] 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 these from the controller:
comments_attributes = params[:ad][:comments_attributes] # this is an array
The above field_tag html output 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]" />
If you enter values between the square brackets, rails will view 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]" %>
would be interpreted by the controller as a hash with keys "1", "2" and "3". I hope i understand correctly what you needed.
Thanks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With