using an array with fields_for

adamteale picture adamteale · Jun 26, 2012 · Viewed 22.6k times · Source

How can I iterate through an array of objects (all the same model) using fields_for ? The array contains objects created by the current_user.

I currently have:

<%= f.fields_for :descriptionsbyuser do |description_form| %>
<p class="fields">
    <%= description_form.text_area :entry, :rows => 3 %>
    <%= description_form.link_to_remove "Remove this description" %>
    <%= description_form.hidden_field :user_id, :value => current_user.id %>
</p>
<% end %>

But I want to replace the :descriptionsbyuser with an array I created in my controller - @descriptionsFromCurrentUser

This is also inside Ryan Bate's "nested_form_for"

Any pointers would be greatly appreciated!

Adam

Answer

barelyknown picture barelyknown · Jul 8, 2014

To use a collection for fields_for and have it work the way that you expect, the model needs accept nested attributes for the collection. If the collection is an ActiveRecord one-to-many relationship, use the accepts_nested_attributes_for class macro. If the collection is not an ActiveRecord one-to-many relationship, you'll need to implement a collection getter and a collection attributes setter.

If it is an ActiveRecord relationship:

class Person
  has_many :projects

  # this creates the projects_attributes= method
  accepts_nested_attributes_for :projects
end

If it is a non-ActiveRecord relationship:

class Person
  def projects
    ...
  end

  def projects_attributes=(attributes)
    ...
  end
end

Either way, the form is the same:

<%= form_for @person do |f| %>
  ...
  <%= f.fields_for :projects, @active_projects do |f| %>
    Name: <%= f.text_field :name %>
  <% end %>
  ...
<% end %>