views:

21

answers:

1

I have a User model, Person model and Company model.

a User has many companies through Person and vice versa.

But i would like to be able to populate People and Companies that are not tied to Users that can be tied later.

class User < ActiveRecord::Base
  attr_accessible :name
  has_many :people
  has_many :companies, :through => :people
end

class Person < ActiveRecord::Base
  attr_accessible :user_id, :company_id
  belongs_to :users
  belongs_to :companies
end

class Company < ActiveRecord::Base
  attr_accessible :name
  has_many :people
  has_many :users, :through => :person
end

now in the console i want to be doing the following

User.find(1).companies

then it should find me the companies in which user(1) is a person of interest.

Have I got this wrong, is there a small change that I should be making.

A: 

You can't "belong_to" more than one, your belongs_to :users and belongs_to :companies associations won't work that way. Companies-to-people need to be connected through another join table called Employment:

class Person < ActiveRecord::Base
  has_many :employments
  has_many :companies, :through => :employments
end

class Employment < ActiveRecord::Base
  belongs_to :person
  belongs_to :company
end

class Company < ActiveRecord::Base
  has_many :employments
  has_many :people, :through => :employments
end

Similarly, if a Person can be owned by more than one User then you will need a join model between those two entities as well.

There is currently no way to query a nested has_many through, but there are workarounds through plugins and patches.

Andrew Vit
person was supposed to be my join table, is kinda messed it up
Joseph Le Brech