19

如何使用 fields_for 遍历对象数组(所有相同的模型)?该数组包含由 current_user 创建的对象。

我目前有:

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

但我想用我在控制器中创建的数组替换 :descriptionsbyuser - @descriptionsFromCurrentUser

这也在 Ryan Bate 的“nested_form_for”中

任何指针将不胜感激!

亚当

4

4 回答 4

38

要使用集合fields_for并使其按您期望的方式工作,模型需要接受集合的嵌套属性。如果集合是ActiveRecord一对多关系,请使用accepts_nested_attributes_for类宏。如果集合不是ActiveRecord一对多关系,则需要实现集合获取器和集合属性设置器。

如果是ActiveRecord关系:

class Person
  has_many :projects

  # this creates the projects_attributes= method
  accepts_nested_attributes_for :projects
end

如果是非ActiveRecord关系:

class Person
  def projects
    ...
  end

  def projects_attributes=(attributes)
    ...
  end
end

无论哪种方式,形式都是相同的:

<%= form_for @person do |f| %>
  ...
  <%= f.fields_for :projects, @active_projects do |f| %>
    Name: <%= f.text_field :name %>
  <% end %>
  ...
<% end %>
于 2014-07-08T11:14:25.043 回答
23

文档fields_for清楚地向您展示了使用数组的方式:

或要使用的集合:

<%= 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这是你的数组。

于 2012-06-26T17:26:26.840 回答
7



如果您正在处理直接数据并且想要在不使用任何这些@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 %>

你的参数数据应该像这样返回

"team" => {
  "people" => [
    {"first_name" => "Michael", "last_name" => "Jordan"},
    {"first_name" => "Steve", "last_name" => "Jobs"},
    {"first_name" => "Barack", "last_name" => "Obama"}
  ]
}
于 2015-02-19T00:05:13.003 回答
5

几乎不知道的答案的补充(由于声誉点而无法添加为评论)-

对于非活动记录的情况,persisted?除了*_attributes=(attributes).

于 2015-04-20T15:50:45.257 回答