Dudo
Dudo

Reputation: 4169

rails has_many through double?

class Foo < ActiveRecord::Base
has_many :bar

class Bar < ActiveRecord::Base
belongs_to :foo
has_many :baz

class Baz < ActiveRecord::Base
belongs_to :bar

I'm after all of Foo's bazs (Foo having many Baz because of Bar's relation). I'm thinking of just adding a has_many :baz to Foo, and a belongs_to :foo on Baz, but I feel like there's a relationship that I'm missing here.

Should I just use a scope? or is there a relation I can put on Foo to get all the baz?

Upvotes: 0

Views: 188

Answers (1)

j-dexx
j-dexx

Reputation: 10406

You should be able to just add a through.

class Foo < ActiveRecord::Base
  has_many :bars
  has_many :bazes, through: :bars
end

Have a look at http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association for more information.

Upvotes: 3

Related Questions