shaneburgess
shaneburgess

Reputation: 15872

has_many inheritance

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?

Upvotes: 0

Views: 167

Answers (1)

Harish Shetty
Harish Shetty

Reputation: 64363

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

Upvotes: 1

Related Questions