get all products of category and child categories (rails, awesome_nested_set)

前端 未结 3 1516
孤街浪徒
孤街浪徒 2021-02-15 14:50

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.

3条回答
  •  滥情空心
    2021-02-15 15:53

    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

提交回复
热议问题