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

我查看了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) 

你为什么不实际使用AREL作为核心。 一旦你到达实际的表范围,你可以使用Arel :: Relation,它完全不同于ActiveRecord实现本身。 我真的相信ActiveRecord :: Relation是围绕Arel :: Relation&Arel :: Table的包装器的完全不同(并且被破坏)的实现。 我选择使用Arel作为核心,通过Thing.scoped.table(Arel :: Table)这是活动的记录样式OR Arel :: Table.new(:table_name),它给了我一个新的Arel :: Table(我的首选方法)。 从这里你可以做到以下几点。

 posts = Arel::Table.new(:thing, :as => 'p') #derived relation comments = Arel::Table.new(:comments, :as => 'c') # derived relation posts_and_comments = posts.join(comments).on( posts[:id].eq(:comments[:id]) ) # now you can iterate through the derived relation by doing the following posts_and_comments.each {...} # this will actually return Arel::Rows which is another story. # 

Arel :: Row从集合返回一个元组的TRUE定义,该集合将包含Arel :: Header(Arel :: Attributes集合)和元组。

同样稍微冗长一点,我之所以使用Arel是因为它真正将关系模型暴露给我,这是ActiveRelation背后的力量。 我注意到ActiveRecord暴露出类似于Arel所提供的20%,我担心开发人员不会意识到这个NOR他们会理解关系代数的真正核心。 使用条件哈希对我来说是“旧学校”和关系代数世界中的ActiveRecord风格编程。 一旦我们学会脱离基于Martin Fowler模型的方法并采用基于EF Codd关系模型的方法,这实际上是RDBMS几十年来一直试图做的但却非常错误。

我已经冒昧地为ruby社区开始了关于Arel和Relational Algebra的七部分学习系列。 这些video将包括从绝对初学者到高级技术的短video,如自我引用关系和组合下的闭包。 第一个video是http://Innovative-Studios.com/#pilot如果您需要更多信息或者这对您来说不够具有描述性,请告诉我。

Arel的未来前景一片光明。

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

是不是

 Post.includes([:author, :comments]).where(['comments.approved = ?', true]).all 

你在找什么? (摘自官方文件 )