避免在Ruby on Rails中使用嵌套关联和条件的N+1查询



我正在制作一个播客播放器,希望显示最近更新的提要列表,以及最近发布的条目的剩余播放时间的详细信息。

所以视图看起来像这样:

@feeds.each do |f|
puts @feed.rss_image.url
puts @feed.most_recent_entry.published_at
if play = @feed.most_recent_entry.most_recent_play_by(@user)
puts play.remaining
end
end

我的模型如下:

class Feed < ApplicationRecord
has_one :rss_image, as: :rss_imageable
has_many :entries, dependent: :destroy
has_one :most_recent_entry, -> { order(published_at: :desc) }, class_name: "Entry"
has_many :plays, dependent: :destroy
end
class Entry < ApplicationRecord
belongs_to :feed, touch: true
has_many :plays, dependent: :destroy
has_one :most_recent_play, -> { order(updated_at: :desc) }, class_name: "Play"
def most_recent_play_by(user)
plays.by(user).order(updated_at: :desc).first
end
end
class Play < ApplicationRecord
belongs_to :entry
belongs_to :feed
belongs_to :user
scope :by, ->(user) { where(user: user) }
def self.most_recent_by(user)
by(user).order(updated_at: :desc).first
end
end

我的查询是:

@feeds = Feed
.joins(:entries)
.includes(:rss_image, most_recent_entry: :most_recent_play)
.where(most_recent_entry: {plays: {user: @user}})
.group(:id)
.order("max(entries.published_at) DESC")
.limit(10)

但是这个错误是:

PG::GroupingError: ERROR:  column "rss_images.id" must appear in the GROUP BY clause or be used in an aggregate function

是否有可能在没有N+1查询的情况下实现这一点?谢谢!

看看Bullet gem,它有助于减少查询数量并消除n+1。在这种情况下,它应该建议您如何修改查询。添加.includes(:entries) ....

最新更新