I am working on a project and there is a complex query that takes 10 seconds or so to perform. I realize that there is an N + 1 query happening but I am new to rails and I am not sure how to fix it. The controller code is :
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
the package model has
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
the channels model has:
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
I also want to mention that filters is usually empty. If I am missing any info please feel free to comment and I will add it. Thanks for your time!
Here is the #packages method from the controller.
def packages
@plan ? @plan.packages : Package
end
Here is the view: 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