2010-01-21 34 views
0

我想建立的東西,這樣一個人可以有多個電子郵件地址和電子郵件地址,只有一個人,而是因爲我也有叫公司其他型號也可以有多個電子郵件地址,我不希望有列COMPANY_ID,並在電子郵件表爲person_id,所以我想我能做到......HAS_ONE:穿過聯接模型

person.rb

的has_many:person_emails 的has_many:電子郵件,:通過=>: person_emails

person_emails.rb

belongs_to的:人 belongs_to的:電子郵件

email.rb

HAS_ONE:person_email HAS_ONE:人:通過=>:person_email

現在所發生的事情是......

p = Person.first#=> 「聶」 p.emails#=>顯示所有郵件聶有 p.person_emails#=>顯示所有person_email了聶

聯合表中的記錄

e = Email.first#=> Nik的電子郵件地址之一 e.person_email#=>顯示此電子郵件的唯一一個person_email聯合表記錄 e.person#失敗,說未知列「people.email_id」中where子句

我想... e.person#=>「聶」

有沒有人有一個想法,這個問題可能是什麼?

謝謝

回答

4

你的情況建議使用多態關聯,這比has_many :through協會乾淨多了。例如:

class Person 
    has_many :emails, :as => :emailable 
end 

class Company 
    has_many :emails, :as => :emailable 
end 

class Email 
    belongs_to :emailable, :polymorphic => true 
end 

你完全可以擺脫你的PersonEmails類。在數據庫中,你emails表將是這個樣子:關聯的模型的

create_table :emails do |t| 
    t.string :address 
    t.string :emailable_type 
    t.integer :emailable_id 
end 

emailable_type列存儲的名字,你的情況"Person""Company"emailable_id存儲相關對象的ID。欲瞭解更多信息,請參閱「多態關聯」 the Rails API documentation