Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails nested attributes array

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?

like image 991
alnafie Avatar asked Mar 24 '23 16:03

alnafie


1 Answers

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

like image 178
Vivek Parihar Avatar answered Apr 05 '23 23:04

Vivek Parihar