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)
| 归档时间: |
|
| 查看次数: |
3758 次 |
| 最近记录: |