ActiveRelation将如何影响轨道“包括()的功能? [英] How will ActiveRelation affect rails' includes() 's capabilities?

查看:335
本文介绍了ActiveRelation将如何影响轨道“包括()的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查了一下阿雷尔的来源,有些ActiveRecord的来源Rails的3.0,但我似乎无法搜集了自己一个很好的答案,阿雷尔是否会改变我们的使用包括()的能力,构建查询时,变得更好。

有情况下,当人们可能要修改一个ActiveRecord的条件:包括查询2.3.5及之前,为这将返回的关联记录。但据我所知,这是不是编程方式成立的所有:包括查询:

(我知道有些AR-发现,包括使T#{N} .C#{M-}重命名为所有的属性,以及一个可以想见,添加条件,这些查询来限制连接台的效果;而另一些则n_joins + 1号在ID查询设置重复,而我不知道怎么一会破解AR编辑这些迭代查询。)

威尔·阿雷尔使我们能够构建在使用包括()?

这指定生成的关联模型对象的ActiveRecord查询

例如:

 网​​友:的has_many帖子(的has_many:评论)

User.all(:包括=>:帖子)#SAY我想要的职位对象有自己的
 #COMMENT计数装不添加comment_count列`posts`。

#At后的水平,我们可以做到这一点是:
posts_with_counts = Post.all(:选择=>职位*,COUNT(comments.id)为comment_count。,
         :加入=> 左外连接上comments.post_id = posts.id评论',
         :GROUP_BY => posts.id)#i的信

#But似乎是不可能这样做的,而连接这些对象后每
  #user还有,而不运行User.all(),然后zippering物体进入
  #some其他集合(丑)
  #OR运行posts.group_by(安培;:用户)(甚至是丑陋,与n用户查询)
 

解决方案

的ActiveRecord ::关系是围绕基地#的find_by_sql一个相当薄弱的包装,所以:有没有延续查询以任何方式将其纳入

I've looked over the Arel sources, and some of the activerecord sources for Rails 3.0, but I can't seem to glean a good answer for myself as to whether Arel will be changing our ability to use includes(), when constructing queries, for the better.

There are instances when one might want to modify the conditions on an activerecord :include query in 2.3.5 and before, for the association records which would be returned. But as far as I know, this is not programmatically tenable for all :include queries:

(I know some AR-find-includes make t#{n}.c#{m} renames for all the attributes, and one could conceivably add conditions to these queries to limit the joined sets' results; but others do n_joins + 1 number of queries over the id sets iteratively, and I'm not sure how one might hack AR to edit these iterated queries.)

Will Arel allow us to construct ActiveRecord queries which specify the resulting associated model objects when using includes()?

Ex:

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)

解决方案

ActiveRecord::Relation is a fairly weak wrapper around Base#find_by_sql, so :include queries are not extended in any way by its inclusion.

这篇关于ActiveRelation将如何影响轨道“包括()的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆