Alter previous method on all versions models

This is to prevent redoing the same SQL query which wasn't being cached.
This commit is contained in:
BrokenEagle
2020-02-08 06:46:58 +00:00
parent d2021256f0
commit 76dcccb7de
6 changed files with 32 additions and 10 deletions

View File

@@ -92,13 +92,16 @@ class PostArchive < ApplicationRecord
end
def previous
# 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 && 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
@previous ||= begin
# 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 && post.association(:versions).loaded?
ver = [post.versions.sort_by(&:version).reverse.find { |v| v.version < version }]
else
ver = PostArchive.where("post_id = ? and version < ?", post_id, version).order("version desc").limit(1).to_a
end
end
@previous.first
end
def visible?