我查看了 Arel 源代码和 Rails 3.0 的一些 activerecord 源代码,但我似乎无法为自己找到一个好的答案,即在构建查询时 Arel 是否会改变我们使用包含()的能力, 为了更好。
在某些情况下,可能需要修改 activerecord 的条件:包括 2.3.5 及之前的查询,以获取将返回的关联记录。但据我所知,对于所有 :include 查询来说,这在编程上是站不住脚的:
(我知道一些 AR-find-includes 使 t#{n}.c#{m} 重命名所有属性,并且可以想象为这些查询添加条件以限制连接集的结果;但其他人则 n_joins + 1 number对 id 集的查询是迭代的,我不确定如何破解 AR 来编辑这些迭代的查询。)
Arel 是否允许我们在使用 include() 时构造 ActiveRecord 查询来指定生成的关联模型对象?
前任:
User :has_many posts( has_many :comments)
User.all(:include => :posts) #say I wanted the post objects to have their
#comment counts loaded without adding a comment_count column to `posts`.
#At the post level, one could do so by:
posts_with_counts = Post.all(:select => 'posts.*, count(comments.id) as comment_count',
:joins => 'left outer join comments on comments.post_id = posts.id',
:group_by => 'posts.id') #i believe
#But it seems impossible to do so while linking these post objects to each
#user as well, without running User.all() and then zippering the objects into
#some other collection (ugly)
#OR running posts.group_by(&:user) (even uglier, with the n user queries)