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.