好吧,我们再试试。代码取自
RB's screencast
使用替换的对象名称:
<% form_for @parent_object do |f| %>
<%= f.error_messages %>
<!-- some field of parent object here -->
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<% f.fields_for :child_objects do |builder| %>
<!-- some fields for child objects -->
<p>
<%= builder.label :content, "Some content for child object" %><br />
<%= builder.text_area :content, :rows => 3 %>
<%= builder.check_box :_destroy %>
<%= builder.label :_destroy, "Remove child object" %>
</p>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>
这是一张
@parent_object
:child_objects
. 当然,您必须用自己的字段替换字段。
def new
@parent_object = ParentObject.new
3.times { @parent_object.child_objects.build }
end
在
edit
方法,你会:
def edit
@parent_object = ParentObject.find(params[:id])
3.times { @parent_object.child_objects.build }
end
要使其工作,需要为子对象定义嵌套属性:
class ParentObject < ActiveRecord::Base
has_many :child_objects, :dependent => :destroy
accepts_nested_attributes_for :child_objects
end
中的更新方法
parent_object_controller.rb
def update
@parent_object = ParentObject.find(params[:id])
if @parent_object.update_attributes(params[:parent_object])
flash[:notice] = "Successfully updated parent object."
redirect_to @parent_object
else
render :action => 'edit'
end
end
但多亏了
accepts_nested_attributes_for
在ParentObject中,也将创建嵌套实例。
source code for this episode
来自github。