Ruby on rails Rails模型属于一个模型或另一个模型
对于CRM应用程序,我希望能够将个人模型直接关联到帐户模型或公司模型,而公司模型又与帐户模型关联。另外,我想将地址模型与公司或个人相关联。这就是我的想法:Ruby on rails Rails模型属于一个模型或另一个模型,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,对于CRM应用程序,我希望能够将个人模型直接关联到帐户模型或公司模型,而公司模型又与帐户模型关联。另外,我想将地址模型与公司或个人相关联。这就是我的想法: class Account has_many :Persons has_many :Companies end class Person belongs_to :Account belongs_to :Company has_one :Address end class Company be
class Account
has_many :Persons
has_many :Companies
end
class Person
belongs_to :Account
belongs_to :Company
has_one :Address
end
class Company
belongs_to :Account
has_many :Persons
has_one :Address
end
class Address
belongs_to :Person
belongs_to :Company
end
因此,根据协会的不同,帐户可以是“个人帐户”或“商业帐户”。它们将是相互排斥的。我计划在Person表中包含外键account\u id和company\u id。出于同样的原因,我会在地址表中有外键person_id和company_id。在每种情况下,一个外键都是空的
这在Rails中可以吗?如果没有,任何建议都将不胜感激。看看多态关联。我想这就是你想要的:
问候Sven您可以使用模型验证来确保只存在一种类型的关联。不确定更大的答案是什么…谢谢斯文!这正是我需要的。只需阅读“TheRails3Way”中的多态关联。我感谢你的帮助。
class Account
belongs_to :User, :polymorphic => true
end
class Person
belongs_to :Account, :as => :User
belongs_to :Company
has_one :Address, :as => :User
end
class Company
belongs_to :Account, :as => :User
belongs_to :Persons
has_one :Address, :as => :User
end
class Address
belongs_to :User, :polymorphic => true
end
...