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

前端 未结 3 1518
孤街浪徒
孤街浪徒 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:26

    Extending charlysisto 's answer, when you are dealing with has_and_belongs_to_many categories, you will soon find out that the brute force perspective is quite slow... You need some kind of "middleware" to make it faster...

    socjopata 's answer gives a good approach of how to improve this. So, you use the definition

    def branch_ids
      self_and_descendants.map(&:id).uniq 
    end
    

    in your category.rb file (model).

    Then, for example, in your controller (example with pagination):

    @category = Category.find... # whatever
    branches  = @category.branch_ids
    @prodcats = ProductCategory.select('distinct product_id')
                               .where('category_id IN (?)',branches)
                               .order(:product_id)
                               .paginate(page: params[:page], :per_page => 25)
    ids       = @prodcats.map(&:product_id)
    @products = Product.where('id IN (?)', ids)
    

    Finally, in your view, you will need a little "technique" in order to have pagination. You will paginate on @prodcats, not @products...

    <%= will_paginate @prodcats %>
    <% @products.each do |product| %>
        ....
    <% end %>
    

    This approach is way faster, WHEN DEALING WITH many_to_many, though not 100% politically correct, I must admit.

提交回复
热议问题