0

Say I have a series of nested resources (Magazine, Edition, and Ad) in a Rails application, such that magazines have many editions, which subsequently have many ads.

How can I do a query to produce all ads in all editions of a given magazine, and then order them, for example, by date created?

Ideally, I'd like to produce an array with all the results using a single SQL query, as opposed to doing a query for each edition and then combining the subsequent arrays.

Ryan Atallah
  • 2,977
  • 26
  • 34

1 Answers1

1

Use has_many :through.

class Magazine < ActiveRecord::Base
  has_many :editions
  has_many :ads, :through => :editions
end

@magazine.ads.order('created_at')

edit Read the docs on has_many :through. It's powerful stuff.

bricker
  • 8,911
  • 2
  • 44
  • 54