7

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

3 回答 3

4

您为什么不实际使用 AREL 作为其核心。一旦你深入到实际的表范围,你就可以使用 Arel::Relation,它与 ActiveRecord 实现本身完全不同。我真的相信 ActiveRecord::Relation 是围绕 Arel::Relation 和 Arel::Table 的包装器的完全不同(并且被破坏)的实现。我选择使用 Arel 作为其核心,要么执行活动记录样式 Thing.scoped.table (Arel::Table) 要么 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% 的内容,我担心开发人员不会意识到这一点,他们也不会理解关系代数的真正核心。使用条件哈希对我来说是“老派”和关系代数世界中的 ActiveRecord 风格编程。一旦我们学会摆脱基于 Martin Fowler 模型的方法并采用基于 EF Codd 关系模型的方法,这实际上就是 RDBMS 几十年来一直在尝试做的事情,但却犯了很大的错误。

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

Arel 的未来一片光明。

于 2010-05-20T22:24:37.617 回答
3

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

于 2010-05-31T19:25:20.407 回答
1

不是吗

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

你在找什么?(取自官方文档

于 2011-02-06T21:12:42.743 回答