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
我认为第二种情况下的第一个查询应该看作第一种情况下的第一个查询。 关于如何实现它的任何想法?
答案 0 :(得分:0)
由于您在第二个ActiveRecord查询中引用了另一个表,因此Rails“巧妙地”推断出您想要eager_load
而不是preload
。