has_one:通过连接模型

时间:2010-01-21 22:39:07

标签: ruby-on-rails activerecord has-one

我想构建一些东西,以便一个人可以拥有多个电子邮件地址,一个电子邮件地址只有一个人,但因为我还有另一个名为公司的模型也可以拥有许多电子邮件地址,我不想在电子邮件表中有列company_id和person_id,所以我想我可以做...

person.rb

has_many:person_emails has_many:电子邮件,:through => :person_emails

person_emails.rb

belongs_to:person belongs_to:电子邮件

email.rb

has_one:person_email has_one:person,:through => :person_email

现在发生的事情是......

p = Person.first#=> “聂” p.emails#=>显示Nik提供的所有电子邮件 p.person_emails#=>显示Nik

的所有person_email联合表记录

e = Email.first#=> Nik的电子邮件地址之一 e.person_email#=>显示此电子邮件的唯一一个person_email联合表记录 e.person#在where子句

中未能说出未知列“people.email_id”

我想...... e.person#=> “聂”

有谁知道问题可能是什么?

谢谢

1 个答案:

答案 0 :(得分: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

相关问题