2011-12-12 61 views
0

我有3種型號:帳戶,組織和個人嵌套資源兩款車型

Account 
    has many Organizations 
    has many People 
Organization 
    belongs to Account 
    has many People 
People 
    belongs to Organization 
    belongs to Account 

這裏的問題是,創建一個新的賬戶時,組織和個人以相同的形式,如何寫ACCOUNT_ID和organization_id到people表?

+0

請提供表單結構,當前正在使用的控制器動作代碼和任何其他詳細信息(如,如果您使用的是accepted_nested_attributes_for)等 – clyfe

回答

1

你需要設置你的模型是這樣的:

應用程序/模型/ account.rb

class Account < ActiveRecord::Base 
    has_many :organizations 
    accepts_nested_attributes_for :organizations 
end 

應用程序/模型/ organization.rb

class Organization < ActiveRecord::Base 
    has_many :people 
    accepts_nested_attributes_for :people 
end 

然後,您將在您的AccountsController中設置new動作,如下所示:

class AccountsController < ApplicationController 
    def new 
    @account = Account.new 
    organization = @account.organizations.build 
    person = @account.people.build 
    end 
end 

爲什麼?好了,因爲你設置的形式app/views/accounts/new.html.erb這樣的:

<%= form_for(@account) do |account| %> 
    <%# account fields go here, like this: %> 
    <p> 
    <%= account.label :name %> 
    <%= account.text_field :name %> 
    </p> 

    <%# then organization fields, nested inside the account (which is what account represents) %> 
    <%# this will create a new set of fields for each organization linked to the account %> 

    <%= account.fields_for :organizations do |organization| %> 
    <p> 
     <%= account.label :name %> 
     <%= account.text_field :name %> 
    </p> 

    <%# and finally, people %> 
    <%= organization.fields_for :people do |person| %> 
     <p> 
     <%= person.label :name %> 
     <%= account.text_field :name %> 
     </p> 
    <% end %> 
    <% end %> 
<% end %> 

這些字段會那麼所有回傳給在AccountsControllercreate動作嵌套在params[:account]。你對付他們這樣的:

class AccountsController < ApplicationController 
    def create 
    @account = Account.new(params[:account]) 
    if @account.save 
     # do something here like... 
     redirect_to root_path, :notice => "Account created!" 
    else 
     # 
     flash[:error] = "Account creation failed!" 
     render :new 
    end 
    end 
end 

因爲你定義在AccountOrganization車型都accepts_nested_attributes_for,該PARAMS將被成功解析,當它創建帳戶,將創建組織,並將其鏈接到帳戶,然後創建該人員並將其鏈接到組織。

完成!

+0

嗨,瑞恩!乾草不是accepted_nested_attributes_爲安全問題在這裏,因爲它可能是一個公共的形式,它是一個has_many關係(可以是工程提交太多的孩子)?我寧願有3個獨立的哈希,添加:inverse_of關係,建立在激光2關係和保存。 – clyfe

+0

如果您擔心,您可以在控制器中進行檢查。如果你建立一個白癡證明系統... –

+0

我做到了這一點:http://pastie.org/3010947,我得到錯誤「組織人員帳戶不能爲空」和「組織人員組織不能爲空」,因爲我驗證了account_id和organization_id的存在 – leonel