使用带有fields_for的数组
如何使用fields_for迭代一组对象(所有相同的模型)? 该数组包含current_user创建的对象。
我目前有:
3 %> current_user.id %>
但我想用我在控制器中创建的数组替换:descriptbyuser – @descriptionsFromCurrentUser
这也是Ryan Bate的“nested_form_for”内部
任何指针将不胜感激!
亚当
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
这是你的数组。
要使用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
无论哪种方式,forms都是一样的:
<%= form_for @person do |f| %> ... <%= f.fields_for :projects, @active_projects do |f| %> Name: <%= f.text_field :name %> <% end %> ... <% end %>
我发现这是最干净的方式
如果您正在处理直接数据并希望在不使用任何@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"} ] }
一个不为人知的答案的补充(由于声誉点无法添加评论) –
对于非activerecord案例,我还要定义persisted?
在我的class级中除了*_attributes=(attributes)
。