2012-03-29 60 views
1

我有兩個表通過第三個表具有多對多關係。在第三個表中是我在建立兩個表之間的關係時需要分配的一段數據,我如何使用ActiveRecords構建方法來分配這些數據?activerecord中映射表中存儲的與元數據的多對多關係

下面是代碼來說明我的意思:

class Company < Contact 

    has_many :contact_companies 
    has_many :people, :through => :contact_companies 
    accepts_nested_attributes_for :people, :allow_destroy => true 
    accepts_nested_attributes_for :contact_companies 

end 


class Person < Contact 

    has_many :contact_companies 
    has_many :companies, :through => :contact_companies 
    accepts_nested_attributes_for :companies, :allow_destroy => true 
    accepts_nested_attributes_for :contact_companies 
end 


class ContactCompany < ActiveRecord::Base 
    belongs_to :person 
    belongs_to :company 
end 

ContactCompany包含一個名爲「位置」的數據成員。我想要做的是一樣的東西:

c = Person.new 
c.companies.build(:name => Faker::Company.name, :position => positions.sample) 

編輯:

當我嘗試上面的代碼,我得到「未知屬性:位置」。

回答

1

c.companies.build行嘗試構建一個Company對象,該對象不具有position屬性(ContactCompany),因此出現此錯誤。它看起來像你試圖設置兩個不同型號的屬性,所以你必須確保你在正確的型號設置適當的屬性:

# you can chain these calls but I separated them for readability 
cc = c.contact_companies.build(:position => positions.sample) 
cc.build_company(:name => Faker::Company.name) 
+0

謝謝!我其實昨天已經想清楚了,但直到8小時後我纔回答自己的問題,到那時我正在家餵養我6周大的寶寶。 :) – 2012-03-30 14:29:39