views:

33

answers:

1

I have inherited a web app with the following tables: Categories, SubCategories and Pages. Pages has category_id and sub_category_id columns.

I need to write an efficient query to eager load pages by category and sub_category for iterate in my view (crude example follows):

- Category One (categories.each do |category|...)
-- Page One    (category.pages.each do |page|...)
-- SubCategory One (category.sub_categories.each do |sub_category|...
---- Page Two (sub_category.pages.each do |page|...)

Category.rb:

class Category < ActiveRecord::Base 
  has_many :pages
  has_many :sub_categories
end

SubCategory.rb:

class SubCategory < ActiveRecord::Base
  belongs_to :category
  has_many :pages
end

Page.rb:

class Page < ActiveRecord::Base
  belongs_to :category
  belongs_to :sub_category

  scope :active_pages, :conditions => {:is_active => true}
end

I've experimented with queries like the following with little success where the sub_categories are concerned:

Category.includes(:sub_categories, :pages).where('pages.is_active = 1')

Categories works great, but I'm not sure how to eager load the sub_categories. Thanks in advance, any help is greatly appreciate.

A: 

according to this article which I was just looking at something like this might do what you want:

Category.find( :all, :include => [ :pages, { :sub_categories => :pages } ] )
Noel Walters
Thanks, Noel. This worked like a charm (I rewrote the syntax for Activerecord 3) and rendering went from 1200ms to 200ms. Thanks again.
TMB
There's new syntax for Active Record 3 ???? Why wasn't I told about this ?!!! :)
Noel Walters