rails中一个窗体多个模型——fields_for

时间:2014-05-21 04:48:02   收藏:0   阅读:364

借助field_for可以生成表单来处理两个或更多模型对象的数据

先看一个官方的例子,一个表单中有person和permission两个模型,其中每个person包含一个permission

bubuko.com,布布扣
<%= 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 %>  
bubuko.com,布布扣

当一个person包含多个permission时,view代码如下

bubuko.com,布布扣
<%= 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 %>  
bubuko.com,布布扣

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方法

bubuko.com,布布扣
# 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  
bubuko.com,布布扣

 

 

rails中一个窗体多个模型——fields_for,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!