views:

32

answers:

1

I have a model called company that has_many users then users belongs_to company.

class Company < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :company
end

If something belongs to users will it also belong to company?

+1  A: 

You have to use has_many :through association for this.

class Comment < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  belongs_to :company
  has_many   :comments
end

class Company < ActiveRecord::Base
  has_many :users
  has_many :comments, :through => :users
end

Now you can do the following:

c = Company.first
c.users    # returns users
c.comments # returns all the comments made by all the users in the company
KandadaBoggu
Ok that makes sense thanks.
dweebsonduty