开发者

Rails model belongs to either one model or another

For a CRM app, I want to be able to associate a Person model directly to an Account model or to a Company model which in turn is associated to an Account model. Also, I want to associate an Address model to either a Company or a Person. This is what I have in mind:

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

So an Account would be either a "person account" or a "business account" depending on the association. They would be mutually exclusive. I plan to have the foreign keys account_id and company_id in the Person table. By the same token I would have the foreign keys person_id and company_id in the Address table. One foreign key would be null in each case.

Is this okay in Rails? If not, any recommendations would be greatly appreciated.


Take a look at polymorphic associations. I think that's what you are looking for: 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
...

Greetings Sven

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜