这更像是一个“事情为什么会这样”的问题,而不是一个“我不知道怎么做”的问题。
拉关联记录的福音是使用:include因为你会得到一个连接,避免一大堆额外的查询:
Post.all(:include => :comments)
然而,当你查看日志时,没有连接发生:
Post Load (3.7ms) SELECT * FROM "posts"
Comment Load (0.2ms) SELECT "comments.*" FROM "comments"
WHERE ("comments".post_id IN (1,2,3,4))
ORDER BY created_at asc)
它采用了一种捷径,因为它一次拉出了所有的注释,但它仍然不是一个连接(所有文档似乎都是这么说的)。我能得到一个连接的唯一方法是使用:joins而不是:include:
Post.all(:joins => :comments)
日志显示:
Post Load (6.0ms) SELECT "posts".* FROM "posts"
INNER JOIN "comments" ON "posts".id = "comments".post_id
Am I missing something? I have an app with half a dozen associations and on one screen I display data from all of them. Seems like it would be better to have one join-ed query instead of 6 individuals. I know that performance-wise it's not always better to do a join rather than individual queries (in fact if you're going by time spent, it looks like the two individual queries above are faster than the join), but after all the docs I've been reading I'm surprised to see :include not working as advertised.
也许Rails意识到了性能问题,除非在某些情况下才会加入?