发布有关如何预加载帖子集合的最后评论的部分解决方案
首先您需要具备以下条件last_comment
协会:
class Post < ApplicationRecord
has_many :comments, dependent: :destroy
has_one :last_comment, -> { order(id: :desc) }, class_name: "Comment"
end
它适用于preload
and includes
在 Rails 5.2 中并生成以下 SQL 查询:
Post.includes(:last_comment)
Post Load (0.2ms) SELECT "posts".* FROM "posts" LIMIT ? [["LIMIT", 11]]
Comment Load (0.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ? ORDER BY "comments"."id" DESC [["post_id", 1]]
这个解决方案的问题是当我使用joins
它忽略关联范围并生成以下 SQL 查询:
Post.joins(:last_comment)
Post Load (0.2ms) SELECT "posts".* FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" LIMIT ? [["LIMIT", 11]]
我能够解决它改变原来的last_comment
关联方式如下:
class Post < ApplicationRecord
has_many :comments, dependent: :destroy
has_one :last_comment, -> {
joins(:post) # <--- Note this change
.where("
comments.id = (
SELECT MAX(comments.id) FROM comments
WHERE comments.post_id = posts.id
)"
)
}, class_name: "Comment"
scope :with_last_comment, -> { joins(:last_comment) }
end
And now Post.with_last_comment
生成以下 SQL:
Post Load (0.3ms) SELECT "posts".* FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" INNER JOIN "posts" "posts_comments" ON "posts_comments"."id" = "comments"."post_id" AND (
comments.id = (
SELECT MAX(comments.id) FROM comments
WHERE comments.post_id = posts.id
)) LIMIT ? [["LIMIT", 11]]
关于 Rails 5.2 中的连接与 Rails 5.1 有何不同的问题仍然悬而未决