1
Post.includes(:comments).order('timestamp DESC'.limit(5).to_a.size

返回 5 并生成以下 SQL 代码:

SELECT "posts".* FROM "posts" ORDER BY "posts"."timestamp" LIMIT 5
SELECT "comments".* FROM "comments" WHERE "comments"."commentable_type" = 'Post' AND "comments"."commentable_id" IN (517, 516, 515, 514, 513)

但是当我尝试添加评论排序时:

Post.includes(:comments).order('posts.timestamp DESC').order('comments.timestamp ASC').limit(5).to_a.size

它返回 1 并生成以下 SQL 代码:

SELECT DISTINCT "posts".id, posts.timestamp AS alias_0, comments.timestamp AS alias_1 FROM "posts" LEFT OUTER JOIN "comments" ON "comments"."commentable_id" = "posts"."id" AND "comments"."commentable_type" IN ('Post') ORDER BY posts.timestamp DESC, comments.timestamp ASC LIMIT 5

SELECT "posts"."id" AS t0_r0, "posts"."content" AS t0_r1, "posts"."timestamp" AS t0_r2, "comments"."id" AS t1_r0, "comments"."content" AS t1_r1, "comments"."timestamp" AS t1_r2, "comments"."commentable_id" AS t1_r3, "comments"."commentable_type" AS t1_r4 FROM "posts" LEFT OUTER JOIN "comments" ON "comments"."commentable_id" = "posts"."id" AND "comments"."commentable_type" IN ('Post') WHERE "posts"."id" IN (517, 517, 517, 517, 517) ORDER BY posts.timestamp DESC, comments.timestamp ASC

我认为第二种情况下的第一个查询应该看起来像第一种情况下的第一个查询。关于如何实施它的任何想法?

4

1 回答 1

0

由于您在第二个 ActiveRecord 查询中引用另一个表,Rails “聪明地”推断出您想要eager_load而不是preload.

参考:http ://blog.arkency.com/2013/12/rails4-preloading/

于 2014-03-06T20:15:59.557 回答