ruby-on-rails - 来自数组优化的 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
我该如何优化它?
解决方案
推荐阅读
- ios - 应用因指南 5.2.5 - 法律 - 知识产权而被拒绝
- xamarin.forms - 如何使用 xamarin 表单从条目控件中删除边框
- timezone - 更改 Amazon Lex 聊天机器人时区
- python - 如何验证数组中的值并执行操作 python whatsapp 框架
- kubernetes - helm install istio 返回禁止错误
- c# - 升级到 .NET Core 2.1 后 Http 请求中断
- javascript - 如何以字符串的形式从 javascript 获取返回值到 android?
- python-3.x - SyntaxError:在 Python 中扫描字符串文字时 EOL
- python - 选择 DataFrame 之间的补列
- python - 使用 JIRA python API 将观察者添加到 JIRA 票证时出错