[英]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.