using an array with fields_for

痴心易碎 提交于 2019-12-02 20:41:07

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.

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 %>

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"}
  ]
}

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!