pools/show: fix N+1 query on pool show page.

Fix a N+1 query when fetching posts to render thumbnails. Also adds
support for the `limit` url param on the posts show page.
This commit is contained in:
evazion
2019-08-08 23:12:40 -05:00
parent 6d171f44c4
commit 4f024d2360
4 changed files with 14 additions and 18 deletions

View File

@@ -39,7 +39,7 @@ class PoolsController < ApplicationController
def show def show
@pool = Pool.find(params[:id]) @pool = Pool.find(params[:id])
@post_set = PostSets::Pool.new(@pool, params[:page]) @posts = @pool.posts.paginate(params[:page], limit: params[:limit], count: @pool.post_count)
respond_with(@pool) respond_with(@pool)
end end

View File

@@ -433,6 +433,7 @@ class PostQueryBuilder
if q[:ordpool].present? if q[:ordpool].present?
pool_id = q[:ordpool].to_i pool_id = q[:ordpool].to_i
# XXX unify with Pool#posts
pool_posts = Pool.joins("CROSS JOIN unnest(pools.post_ids) WITH ORDINALITY AS row(post_id, pool_index)").where(id: pool_id).select(:post_id, :pool_index) pool_posts = Pool.joins("CROSS JOIN unnest(pools.post_ids) WITH ORDINALITY AS row(post_id, pool_index)").where(id: pool_id).select(:post_id, :pool_index)
relation = relation.joins("JOIN (#{pool_posts.to_sql}) pool_posts ON pool_posts.post_id = posts.id").order("pool_posts.pool_index ASC") relation = relation.joins("JOIN (#{pool_posts.to_sql}) pool_posts ON pool_posts.post_id = posts.id").order("pool_posts.pool_index ASC")
end end

View File

@@ -213,21 +213,10 @@ class Pool < ApplicationRecord
end end
end end
def posts(options = {}) # XXX unify with PostQueryBuilder ordpool search
offset = options[:offset] || 0 def posts
limit = options[:limit] || Danbooru.config.posts_per_page pool_posts = Pool.where(id: id).joins("CROSS JOIN unnest(pools.post_ids) WITH ORDINALITY AS row(post_id, pool_index)").select(:post_id, :pool_index)
slice = post_ids.slice(offset, limit) posts = Post.joins("JOIN (#{pool_posts.to_sql}) pool_posts ON pool_posts.post_id = posts.id").order("pool_posts.pool_index ASC")
if slice && slice.any?
slice.map do |id|
begin
Post.find(id)
rescue ActiveRecord::RecordNotFound
# swallow
end
end.compact
else
[]
end
end end
def synchronize def synchronize

View File

@@ -15,9 +15,15 @@
<%= render "posts/partials/common/inline_blacklist" %> <%= render "posts/partials/common/inline_blacklist" %>
<section> <section>
<%= @post_set.presenter.post_previews_html(self) %> <% if @pool.post_count == 0 %>
<%= render "post_sets/blank" %>
<% else %>
<% @posts.each do |post| %>
<%= PostPresenter.preview(post, pool_id: @pool.id) %>
<% end %>
<%= numbered_paginator(@post_set) %> <%= numbered_paginator(@posts) %>
<% end %>
</section> </section>
</div> </div>
</div> </div>