0

I am trying to understand how to make a nested form of my models but I am struggeling with understanding how and what I need to do it. I have been reading the Rails documentation and looked at the railscast but they just mention the accepts_nested_attributes_for method etc without explaining. Can someone please help?

4

1 回答 1

1

根据 Rails 的 API,据说:

嵌套属性允许您通过父级将属性保存在关联记录上...

示例:它展示了我们如何通过 Member 管理帖子,fields_for用于管理表单中的关联字段,将关联模型的名称传递给它,然后遍历所有关联的帖子记录并为每个记录创建一个表单构建器.

#controller
def new
  @member = Member.new
end

#model
class Post < ActiveRecord::Base
  belongs_to :member
end

class Member < ActiveRecord::Base
  has_many :posts
  accepts_nested_attributes_for :posts
end

#form
<%= form_for @member do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <%= f.fields_for :posts do |builder| %>
  <p>
    <%= builder.label :account %><br />
    <%= builder.text_area :account %>
  </p>
  <% end %>
  <p><%= f.submit "Submit" %></p>
<% end %>

Rails API:http ://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

于 2012-08-07T19:19:33.497 回答