I have a set of categories, belonging to a category set. These categories can themselves have a mix of categories (self-referential) and also questions. The models and their relationships are defined & visualized as follows:
class CategorySet < ActiveRecord::Base
has_many :categories
end
class Category < ActiveRecord::Base
belongs_to :category_set
belongs_to :parent_category, :class_name => "Category"
has_many :categories, :class_name => "Category", :foreign_key => "parent_category_id", dependent: :destroy
has_many :questions, dependent: :destroy
end
class Question < ActiveRecord::Base
belongs_to :category
end
Abbrev to CS, C and Q:
CS
|- C
|- Q
|
|- C
|
|- C
| |- Q
|
|- C
|- Q
|- Q
I would like to be able to ask CategorySet.find(1).questions and return all questions in the tree regardless of position. The only ways I can think of use lots of function-based requests and will probably be overkill on sql statements (see below for an example).
Calling CategorySet.find(1).categories finds only the direct descendant categories of the category set. Also, Category.find(id).questions returns only the questions for that category.
I have tried overwriting the .questions method on categories, but that doesn't seem very rails relationship-esque and there must be a better way of doing this? Alo it means I can't do the CategorySet.includes(:questions).all style syntax which greatly reduces the load on the database server