Search code examples
sqlruby-on-railsnested-resources

Rails 3 SQL query inside nested resources


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.


Solution

  • 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.