简体   繁体   中英

Rails simple_form nested attributes

I have 2 models:

class Client < ActiveRecord::Base
  has_many :contact_people

  accepts_nested_attributes_for :contact_people
end

class ContactPerson < ActiveRecord::Base
  belongs_to :client
end

I cand add a new Client or a new ContactPerson separately with no problem.

I want to create a form where I will be able to add them both with a nested form. What would be the recommended way to do this, create a new controller to do this and create new and create action for that, or use the ClientsController and create a new method there?

If a new controller is recommended, how can I access the params? Also, will validations will work here?

Thanks!

You should be using the new and create methods of your ClientsController to do something like this

Class ClientsController < ApplicationController

   def new
      @client = Client.new
      @client.contact_people.build #this is very important
   end

   def create
     @client = Client.new(client_params)

     if @client.save
     redirect_to @client
     else
     render 'new'
     end
   end

   private

   def client_params
     params.require(:client).permit(:client_attr1, :client_attr2,.., contact_people_attributes: [:id, :contact_people_attr1,:contact_people_attr2,..])
   end
 end

And the view code would be something like this

<%= simple_form_for @client, :html => { :multipart => true } do |f| %>
  <% if @client.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@client.errors.count, "error") %> prohibited this client from being saved:</h2>

      <ul>
      <% @client.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

 #your client attributes code here

  <%= f.simple_fields_for :contact_people do |cp| %>
    #your contact_people attributes code here
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

And the validations you are talking about can be set normally in models.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM