【发布时间】:2014-12-03 05:51:35
【问题描述】:
我正在处理一个项目,有一个复杂的查询需要 10 秒左右才能执行。我意识到有一个 N + 1 查询正在发生,但我是 Rails 新手,我不知道如何解决它。控制器代码是:
def index
filters = params.slice(:package_type, :guid)
list = packages
list = list.where(filters) unless filters.empty?
respond_to do |format|
format.html { @packages = list.includes(:classification).order(:priority => :asc) }
format.json { @packages = list.includes(:classification, {channels: [:classification, :genres]}, :extras).order(:priority => :asc) }
end
end
封装模型有
class Package < ActiveRecord::Base
extend FriendlyId
belongs_to :classification
has_many :package_channels
has_many :channels, -> { order(:priority => :asc, :identifier => :asc) }, through: :package_channels
has_many :package_extras
has_many :extras, -> { order(:identifier => :asc) },through: :package_extras
渠道模型有:
class Channel < ActiveRecord::Base
belongs_to :classification
has_many :channel_genres
has_many :genres, through: :channel_genres
has_many :package_channels
has_many :packages, through: :package_channels
我还想提一下,过滤器通常是空的。如果我缺少任何信息,请随时发表评论,我会添加它。感谢您的宝贵时间!
这是来自控制器的#packages 方法。
def packages
@plan ? @plan.packages : Package
end
这里是视图:index.json.jbuilder
json.cache! ["cache", "#{params["plan_id"]}_packages_index"] do
json.array! @packages do |package|
json.partial! 'packages/package_lean', package: package
end
end
【问题讨论】:
-
你能显示你的控制器的
#packages方法吗?你能添加你的视图代码吗?
标签: ruby-on-rails ruby activerecord query-optimization