首页 > 解决方案 > 来自数组优化的 Rails Kaminari

问题描述

问题:我有类别和类别中的产品。代码/查询非常慢。

每个类别都有子类别作为相同的模型。子类别也有产品,也许还有子类别。所以我需要在调用父类时获取所有子类的所有产品。

类别模型

  class Category < ApplicationRecord
      belongs_to :parent, polymorphic: true
      has_many :categories, as: :parent, :dependent => :destroy
      has_many :products, :dependent => :destroy

      def all_products
        @all_products = []
        all_products_find(self)
        return @all_products
      end

      def all_products_find(category)
        @all_products += category.products
        for cat in category.categories
          all_products_find(cat)
        end
      end
    ...
    end

我使用Kaminari对数组进行分页,但是在使用它之前,类别将所有产品都放入数组中,所以它很长。如何在不收集所有产品的情况下进行 paginate_array ?

我的控制器的动作

    @category = Category.find(params[:id])
    if !(@category.nil?)
      @products = @category.all_products #still gathering all products -> slow
      @products_part = Kaminari.paginate_array(@products).page(params[:page]).per(12)
    end

我该如何优化它?

标签: ruby-on-railsrubyactiverecordactivemodelkaminari

解决方案


推荐阅读