Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 958
Corey Quillen Avatar asked Aug 08 '11 19:08

Corey Quillen


1 Answers

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

like image 180
SvenK Avatar answered Sep 26 '22 05:09

SvenK