我有模型消息。它可能由我的数据库中的个人或组织发布。我想调用 update.contact,其中联系人是组织或个人。
class Update < ActiveRecord::Base
has_one :contact
我喜欢使用的决定就像
class Organization < ActiveRecord::Base
belongs_to :update, as: :contact
但是这种方法在 Rails 中不可用。我应该使用多态关联吗?如何组织这个案例的架构?
我有模型消息。它可能由我的数据库中的个人或组织发布。我想调用 update.contact,其中联系人是组织或个人。
class Update < ActiveRecord::Base
has_one :contact
我喜欢使用的决定就像
class Organization < ActiveRecord::Base
belongs_to :update, as: :contact
但是这种方法在 Rails 中不可用。我应该使用多态关联吗?如何组织这个案例的架构?
这听起来像是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
在其中添加等。