Rails simple_form嵌套属性

时间:2014-07-04 15:08:02

标签: ruby-on-rails simple-form nested-forms

我有2个型号:

class Client < ActiveRecord::Base
  has_many :contact_people

  accepts_nested_attributes_for :contact_people
end

class ContactPerson < ActiveRecord::Base
  belongs_to :client
end

我可以分别添加新的Client或新的ContactPerson,但没问题。

我想创建一个表单,我可以用嵌套表单添加它们。建议的方法是什么,创建一个新的控制器来执行此操作并为其创建新的操作并创建操作,或使用ClientsController并在那里创建新方法?

如果建议使用新控制器,我该如何访问参数?此外,验证将在这里工作吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您应该使用 new create ClientsController 方法来执行此操作像这样的东西

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

视图代码就是这样的

<%= 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 %>

您正在谈论的验证可以在模型中正常设置。