Rails模型属于一个模型或另一个模型

Cor*_*len 10 ruby-on-rails ruby-on-rails-3

对于CRM应用程序,我希望能够将Person模型直接关联到Account模型或公司模型,而Company模型又与Account模型相关联.此外,我想将地址模型与公司或人员相关联.这就是我的想法:

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
Run Code Online (Sandbox Code Playgroud)

因此,根据关联,帐户可以是"个人帐户"或"企业帐户".它们是相互排斥的.我打算在Person表中使用外键account_id和company_id.出于同样的原因,我将在地址表中使用外键person_id和company_id.在每种情况下,一个外键将为null.

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

Sve*_*enK 11

看看多态关联.我认为这就是你要找的东西: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
...
Run Code Online (Sandbox Code Playgroud)

问候斯文

  • 谢谢斯文!这正是我所需要的.只需阅读"The Rails 3 Way"中的多态关联.我感谢您的帮助. (2认同)