簡體   English   中英

Rails simple_form嵌套屬性

[英]Rails simple_form nested attributes

我有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並在ClientsController創建一個新方法?

如果建議使用新控制器,如何訪問參數? 此外,驗證是否可以在這里進行?

謝謝!

您應該使用ClientsControllernewcreate方法來執行以下操作

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

您正在談論的驗證可以在模型中正常設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM