has_one :通过连接模型
我想构建一些东西,以便一个人可以拥有多个电子邮件地址,而一个电子邮件地址只能包含一个人,但是因为我还有另一个名为 Company 的模型,它也可以拥有多个电子邮件地址,并且我不想拥有 company_id 列和电子邮件表中的 person_id ,所以我想我可以做...
person.rb
has_many :person_emails has_many :电子邮件, :通过 => :person_emails
person_emails.rb
属于:person 属于:电子邮件
email.rb
has_one :person_email has_one :person, :through =>; :person_email
现在发生的事情是...
p = Person.first #=> “尼克” p.emails#=>显示 Nik 的所有电子邮件 p.person_emails #=> 的所有 person_email 联表记录
显示 Nik e = Email.first #=> Nik 的电子邮件地址之一 e.person_email #=>显示此电子邮件的唯一一条 person_email 联表记录 where 子句中说出未知列“people.email_id”
e.person # 未能在我想要的 ... e.person #=> “尼克”
有人知道问题出在哪里吗?
谢谢
I want to build something so that a person can have many email addresses and an email address has only one person, but because I also have another model called Company that also can have many email addresses, and I don't want to have columns company_id and person_id in the Emails table, so I thought I can do ...
person.rb
has_many :person_emails
has_many :emails, :through => :person_emails
person_emails.rb
belongs_to :person
belongs_to :email
email.rb
has_one :person_email
has_one :person, :through => :person_email
What's happening now is that...
p = Person.first #=> "Nik"
p.emails #=> shows all emails Nik has
p.person_emails #=> shows all person_email joint table records for Nik
e = Email.first #=> one of Nik's email addresses
e.person_email #=> shows this email's one and only one person_email joint table record
e.person # fails saying that unknown column "people.email_id" in where-clause
I'd like...
e.person #=> "Nik"
Does anyone have an idea what the problem might be?
Thank You
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的情况建议使用多态关联,它比
has_many :through
关联干净得多。例如:您可以完全删除
PersonEmails
类。在数据库中,您的emails
表将如下所示:emailable_type
列存储关联模型的名称,在您的情况下为“Person”
或"Company"
,emailable_id
存储关联对象的 ID。有关详细信息,请参阅“多态关联”下的Rails API 文档。Your situation suggests using polymorphic associations, which are much cleaner than
has_many :through
associations. For example:You can get rid of your
PersonEmails
class entirely. In the database, youremails
table will look something like this:The
emailable_type
column stores the name of the associated model, in your case"Person"
or"Company"
, and theemailable_id
stores the id of the associated object. For more information see the Rails API documentation under "Polymorphic Associations".