Reputation: 14279
I have a couple models
class AAA < ActiveRecord::Base
has_many :bbbs, through: :some_other_model
end
class BBB < ActiveRecord::Base
has_many :cccs, through: :yet_another_model
end
Assuming I have a reference to an instance of AAA
, how can I get a flat list of all CCCs
without resorting to inefficient patterns like a.bbbs.map { |x| x.cccs }
?
Upvotes: 0
Views: 76
Reputation: 12836
Since RoR 3.1 you can nest has_many :through
associations.
From 3.1 release notes:
Associations with a :through option can now use any association as the through or source association, including other associations which have a :through option and has_and_belongs_to_many associations.
In your example:
class AAA < ActiveRecord::Base
has_many :bbbs, through: :some_other_model
has_many :cccs, through: :bbbs
end
AAA.first.cccs # => [ccc1, ccc2, ...]
Upvotes: 2