Rails in one form multiple models--fields_for

Source: Internet
Author: User

With Field_for, you can generate forms to process data for two or more model objects

Let's look at an official example where there are two models of person and permission in a form, each of whom contains a permission

<%= form_for (@person) do |person_form| %>     <%= person_form.text_field:first_name%>     <%= person_form.text_field:last _name%>        <% fields_for:p ermission, @person. Permission do |permission_fields|%>       <%= Permission_fields.check_box:admin%>     <% end%>   <% End%>  

When a person contains multiple permission, the view code is as follows

<%= form_for (@person) do |person_form| %>     <%= person_form.text_field:first_name%>     <%= person_form.text_field:last _name%> for in         @person. Permissions%>     "permission[]" , permission do |permission_fields| %>         <%= permission_fields.check_box:admin%>       <% end%>     <% end%> <% End%>  

1, where "permission[ " to ensure that multiple permission object IDs are different, are included in param[]

2, at this time, param[:p erson]={:first_name = V,: last_name = V, :p ermission1=>v,:p ermission2 = v ...}

3, <%=person_form. Fields_for "permission[]", permission do |permission_fields| When%>,

param[:p erson]={:first_name = V,: last_name = V, :p ersom=>{:p ermission1=>v,:p ermission2 = v ...} }

Model Code

# models/.person.rb   def permission_attributes=(permission_attributes)    permission|attributes|       permissions. Build (attributes)    end  End  

In order to correspond to the permission[inside the view]

The Create method in the controller

#persons_controller.rbdefNew @person=person.new3. Times {@person. Permissions.build} enddefCreate @person=person.new (params[:p roject)if@person. Save Flash[:notice]="successfully created project."redirect_to Persons_pathElserender:action='New'End End

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.