having an e-commerce application under development i am trying to get my head around the following problem: I have my categories realized through the awesome_nested_set plugin.
The key with awesome_nested_set is to use a range in the lft column. Here's a code sample of how I do it with a direct association (category has_many articles)
module Category
extend ActiveSupport::Concern
included do
belongs_to :category
scope :sorted, includes(:category).order("categories.lft, #{table_name}.position")
end
module ClassMethods
def tree(category=nil)
return scoped unless category
scoped.includes(:category).where([
"categories.tree_id=1 AND categories.lft BETWEEN ? AND ?",
category.lft, category.rgt
])
end
end # ClassMethods
end
Then somewhere in a controller
@category = Category.find_by_name("fruits")
@articles = Article.tree(@category)
that will find all articles under the categories apples, oranges, bananas, etc etc. You should adapt that idea with a join on categorizations (but are you sure you need a many to many relationship here?)
Anyway I would try this :
class Product < AR
has_many :categorizations
def self.tree(category=nil)
return scoped unless category
select("distinct(products.id), products.*").
joins(:categorizations => :category).where([
"categories.lft BETWEEN ? AND ?", category.lft, category.rgt
])
end
end
Let me know if there's any gotcha