post archives: fix N+1 problem when fetching previous version.

This commit is contained in:
evazion
2017-03-30 16:22:40 -05:00
committed by r888888888
parent 964197d403
commit 1ae5b7ba2f
3 changed files with 9 additions and 3 deletions

View File

@@ -96,7 +96,13 @@ class PostArchive < ActiveRecord::Base
end
def previous
PostArchive.where("post_id = ? and version < ?", post_id, version).order("version desc").first
# HACK: if all the post versions for this post have already been preloaded,
# we can use that to avoid a SQL query.
if association(:post).loaded? && post.association(:versions).loaded?
post.versions.sort_by(&:version).reverse.find { |v| v.version < version }
else
PostArchive.where("post_id = ? and version < ?", post_id, version).order("version desc").first
end
end
def diff(version = nil)