【问题标题】:What type of relations to choose if I want to link 2 models with one如果我想将 2 个模型与一个链接,选择什么类型的关系
【发布时间】:2013-09-21 21:52:06
【问题描述】:
我有模型消息。它可能由我的数据库中的个人或组织发布。
我想调用 update.contact,其中联系人是组织或个人。
class Update < ActiveRecord::Base
has_one :contact
我喜欢使用的决定就像
class Organization < ActiveRecord::Base
belongs_to :update, as: :contact
但这种方法在 Rails 中不可用。
我应该使用多态关联吗?这个案例如何组织架构?
【问题讨论】:
标签:
ruby-on-rails
belongs-to
model-associations
【解决方案1】:
听起来Organization 和Person 可能是同一实体(客户、用户等)的两个不同变体。那么,为什么不为他们两个创建一个共同的父模型呢?这样的父级不一定需要一个表,您可能只需要在其中定义常用方法。 Update 更像是一个动作而不是一个对象,它可以应用于 Contact 对象(通常在其控制器中)。对于Contact 类,可以使用多态关联。所以你可能有:
class Parent < ActiveRecord::Base
# stuff Person and Organization share
end
class Person < Parent
has_one :contact, as: :owner
# Person methods etc.
end
class Organization < Parent
has_one :contact, as: :owner
# Organization stuff
end
class Contact
belongs_to :owner, polymorphic: true
def update
#...
end
# other stuff for Contact
end
然后你可以写成这样的行:
Person.first.contact.update
或者你需要对你的对象做的任何事情。
如果您的Organization 和Person 差别不大,您可以为父类创建一个表,并在其中添加has_one 等。