[英]using an array with fields_for
如何使用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 %>
但我想用我在控制器中创建的数组替换:descriptbyuser - @descriptionsFromCurrentUser
这也是Ryan Bate的“nested_form_for”内部
任何指针将不胜感激!
亚当
要使用fields_for
的集合并使其按预期方式工作,模型需要接受集合的嵌套属性。 如果集合是ActiveRecord
一对多关系,请使用accepts_nested_attributes_for
类宏。 如果集合不是ActiveRecord
一对多关系,则需要实现集合getter和集合属性setter。
如果是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 %>
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
这是你的数组。
我发现这是最干净的方式
如果您正在使用直接数据并希望在不使用任何这些@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 %>
你的params数据应该像这样返回
"team" => {
"people" => [
{"first_name" => "Michael", "last_name" => "Jordan"},
{"first_name" => "Steve", "last_name" => "Jobs"},
{"first_name" => "Barack", "last_name" => "Obama"}
]
}
勉强知道答案的补充(由于声誉点而无法添加评论) -
对于非主动记录的情况,我还必须定义persisted?
在我的班级中除了*_attributes=(attributes)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.