借助field_for可以生成表单来处理两个或更多模型对象的数据
先看一个官方的例子,一个表单中有person和permission两个模型,其中每个person包含一个permission
<%= form_for(@person) do |person_form| %> First name: <%= person_form.text_field :first_name %> Last name: <%= person_form.text_field :last_name %> <% fields_for :permission, @person.permission do |permission_fields| %> Admin : <%= permission_fields.check_box :admin %> <% end %> <% end %>
当一个person包含多个permission时,view代码如下
<%= form_for(@person) do |person_form| %> First name: <%= person_form.text_field :first_name %> Last name: <%= person_form.text_field :last_name %> <% for permission in @person.permissions %> <%= fields_for "permission[]", permission do |permission_fields| %> Admin : <%= permission_fields.check_box :admin %> <% end %> <% end %> <% end %>
1、其中"permission[]"保证了多个permission对象id不同,都包含在param[]中
2、此时,param[:person]={:first_name => v, :last_name => v, :permission1=>v, :permission2 => v...}
3、<%=person_form.fields_for "permission[]", permission do |permission_fields| %>时,
param[:person]={:first_name => v, :last_name => v, :persom=>{:permission1=>v, :permission2 => v...}}
model代码
# models/.person.rb def permission_attributes=(permission_attributes) permission_attributes.each do |attributes| permissions.build(attributes) end end
为了对应view里面的permission[]
controller里的create方法
# persons_controller.rb def new @person= person.new 3.times { @person.permissions.build } end def create @person= Person.new(params[:project) if @person.save flash[:notice] = "Successfully created project." redirect_to persons_path else render :action => ‘new‘ end end