两个单表继承模型之间的关系

发布于 2024-08-15 11:56:54 字数 416 浏览 5 评论 0原文

我有以下两个模型

class ContactField < ActiveRecord::Base
end

class Address < ContactField
end

class Phone < ContactField
end

class Contact < ActiveRecord::Base
end

class Company < Contact
end

class Person < Contact
end

我想要一个联系人,无论是公司还是个人,都有很多ContactFields(地址和电话)...那么我应该把这些有很多放在哪里>属于? 谢谢

I have the following two models

class ContactField < ActiveRecord::Base
end

class Address < ContactField
end

class Phone < ContactField
end

and

class Contact < ActiveRecord::Base
end

class Company < Contact
end

class Person < Contact
end

I want one contact, no matter is it Company or Person, to have many ContactFields(Addresses and Phones)... So where should I put those has many and belongs to?
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

毁梦 2024-08-22 11:56:54

你已经用简单的英语说过了:-)

我想要一个联系人,无论是公司还是个人,都有很多ContactFields(地址和电话)...那么我应该把那些有很多且属于的字段放在哪里呢?谢谢

class Contact < ActiveRecord::Base
 has_many :contact_fields
end

class ContactField < ActiveRecord::Base
 belongs_to :contact
end

,此关系将由地址和电话继承

You already said it in plain english :-)

I want one contact, no matter is it Company or Person, to have many ContactFields(Addresses and Phones)... So where should I put those has many and belongs to? Thanks

class Contact < ActiveRecord::Base
 has_many :contact_fields
end

class ContactField < ActiveRecord::Base
 belongs_to :contact
end

This Relationship will be inherited by both address and phone

笛声青案梦长安 2024-08-22 11:56:54

看起来您正在描述一种归属关系。关联应该在父类中定义,以便子类可以继承它们。

class ContactField < ActiveRecord::Base
  belongs_to :contact
  belongs_to :company, :foreign_key => :contact_id
  belongs_to :person, :foreign_key => :contact_id
end

class Contact < ActiveRecord::Base
  has_many :contact_fields
  has_many :addresses
  has_many :phones
end

但是@contact.contact_fields只会返回ContactField记录。如果您需要任何子类中定义的方法,您始终可以使用变成方法。有几种方法可以解决这个问题。像我一样添加额外的关联。或者使用 ActiveRecord::Base#becomes

Looks like you're describing a belongs to relationship. The associations should be defined in the parent class, so they can be inherited by the subclasses.

class ContactField < ActiveRecord::Base
  belongs_to :contact
  belongs_to :company, :foreign_key => :contact_id
  belongs_to :person, :foreign_key => :contact_id
end

class Contact < ActiveRecord::Base
  has_many :contact_fields
  has_many :addresses
  has_many :phones
end

However @contact.contact_fields will just return ContactField records. If you need the methods defined in any of the sub classes you can always use the becomes method. There are a few ways around that. Such adding the extra associations, like I did. Or using ActiveRecord::Base#becomes

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文