【问题标题】:Rails model belongs to either one model or anotherRails 模型属于一个模型或另一个模型
【发布时间】:2011-08-09 03:55:10
【问题描述】:

对于 CRM 应用,我希望能够将 Person 模型直接关联到 Account 模型或关联到 Company 模型,后者又关联到 Account 模型。另外,我想将 Address 模型与 Company 或 Person 相关联。这就是我的想法:

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_id 和 company_id。出于同样的原因,我将在 Address 表中拥有外键 person_id 和 company_id。在每种情况下,一个外键都将为空。

这在 Rails 中可以吗?如果没有,任何建议将不胜感激。

【问题讨论】:

  • 您可以使用模型验证来确保只存在一种类型的关联。不确定更大的答案是什么......

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

看看多态关联。我认为这就是您要寻找的: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

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
...

你好,斯文

【讨论】:

  • 谢谢斯文!这正是我所需要的。只需阅读“The Rails 3 Way”中的多态关联。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多