问题
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
回答1:
Docs for fields_for clearly shows you the way of using arrays:
Or a collection to be used:
<%= form_for @person do |person_form| %> ... <%= person_form.fields_for :projects, @active_projects do |project_fields| %> Name: <%= project_fields.text_field :name %> <% end %> ... <% end %>
@active_projects
here is your array.
回答2:
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 %>
回答3:
i found this to be the cleanest way
if you are working with straight data and want to send back an array without using any of these @objects
<%= form_for :team do |t| %>
<%= t.fields_for 'people[]', [] do |p| %>
First Name: <%= p.text_field :first_name %>
Last Name: <%= p.text_field :last_name %>
<% end %>
<% end %>
your params data should return like this
"team" => {
"people" => [
{"first_name" => "Michael", "last_name" => "Jordan"},
{"first_name" => "Steve", "last_name" => "Jobs"},
{"first_name" => "Barack", "last_name" => "Obama"}
]
}
回答4:
An addition to barelyknown's answer (wasn't able to add as a comment due to reputation points) -
For the non-activerecord case, I also had to define persisted?
in my class in addition to *_attributes=(attributes)
.
来源:https://stackoverflow.com/questions/11212631/using-an-array-with-fields-for