ActiveRelation将如何影响rails的includes()的功能?

Tim*_*ite 7 ruby activerecord ruby-on-rails active-relation

我查看了Arel源代码,以及Rails 3.0的一些activerecord源代码,但我似乎无法为自己收集一个很好的答案,因为在构造查询时Arel是否会改变我们使用includes()的能力, 为了更好.

有些情况下,人们可能想要修改activerecord上的条件:包括2.3.5及之前的查询,用于返回的关联记录.但据我所知,这对于所有人来说都不是以编程方式成立的:包含查询:

(我知道一些AR-find-includes make t#{n} .c#{m}重命名所有属性,可以想象为这些查询添加条件以限制连接集的结果;但是其他人做n_joins + 1个数字迭代地对id设置的查询,我不确定如何破解AR来编辑这些迭代查询.)

Will Arel允许我们构造ActiveRecord查询,在使用includes()时指定结果关联的模型对象?

例如:

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)
Run Code Online (Sandbox Code Playgroud)

Tim*_*ite 3

ActiveRecord::Relation 是 Base#find_by_sql 的一个相当弱的包装器,因此 :include 查询不会通过其包含以任何方式扩展。