---
title: "Rails 3 ActiveRecord的Relation源码剖析"
author: "pingfeng"
date: "2011-03-01T21:06:11Z"
tags: []
categories: ["编程语言"]
slug: "rails-3-activerecord-relation"
draft: false
lastmod: "2011-03-01T21:06:11Z"
id: 937494
url: "https://pingfeng.iteye.com/blog/937494"
---

Rails3的一大亮点是 AR的query 接口：

1\. 程序员最爱用就是它的及接方式

Uers.where().where().order()....

2\. 还有LasyLoad可以增加灵活性

＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝

但这个Relation还是很让人迷惑的。尤其是一上来：

      delegate :find, :first, :last, :all, :destroy, :destroy\_all, :exists?, :delete, :delete\_all, :update, :update\_all, :to =&gt; :scoped  
      delegate :find\_each, :find\_in\_batches, :to =&gt; :scoped  
      delegate :select, :group, :order, :reorder, :except, :limit, :offset, :joins, :where, :preload, :eager\_load, :includes, :from, :lock, :readonly, :having, :create\_with, :to =&gt; :scoped  
      delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to =&gt; :scoped

这么生猛的操作都被delegate到:scoped上。不熟悉rails的手法，更是不知所云。

NamedScope scoped

知道调用 relation，new出一个relation实例就行了

@relation ||= Relation.new(self, arel\_table)

这样，所以的操作都被delegate到relation实例上。

＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝

relation查询接口都在relation目录下的query\_methods.rb文件中

像order这种简单谓词

 def order(\*args)  
      relation = clone  
      relation.order\_values += args.flatten unless args.blank?  
      relation  
    end

就直接记到实例变量，后面产生sql用。

像where就复杂一些

def where(opts, \*rest)  
      relation = clone  
      relation.where\_values += build\_where(opts, rest) unless opts.blank?  
      relation  
    end

build\_where又调用了predicate\_builder来builderwhere\_value。在这里也是用了arel

================================

这些query动作完后，用all, first, last来向db fetch东西，最重要的东西来了！

调用relation to\_a方法

  def to\_a  
      return @records if loaded?

      @records = eager\_loading? ? find\_with\_associations : @klass.find\_by\_sql(arel.to\_sql)  
...  
      @records  
    end

让are生成to\_sql，还用是AR的base中的connection用查询数据回来

那么arel是如何生成的呢

def build\_arel  
      arel = table

      arel = build\_joins(arel, @joins\_values) unless @joins\_values.empty?

      arel = collapse\_wheres(arel, (@where\_values - \['']).uniq)

      arel = arel.having(\*@having\_values.uniq.reject{|h| h.blank?}) unless @having\_values.empty?

      arel = arel.take(connection.sanitize\_limit(@limit\_value)) if @limit\_value  
      arel = arel.skip(@offset\_value) if @offset\_value

      arel = arel.group(\*@group\_values.uniq.reject{|g| g.blank?}) unless @group\_values.empty?

      arel = arel.order(\*@order\_values.uniq.reject{|o| o.blank?}) unless @order\_values.empty?

      arel = build\_select(arel, @select\_values.uniq)

      arel = arel.from(@from\_value) if @from\_value  
      arel = arel.lock(@lock\_value) if @lock\_value

      arel  
    end

arel本身可以不断及连。

＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝

到时，真相大白。

relation是一个逻辑体，可以不断及联。are是一个sql factory。 AR:base是实体，有数据库连接。

那么要hook住AR的query，只要hook在relation的to\_a方法上。

＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝

设计上可以参考是：

1\. 及联，类似decorator模式  
   
2\. base, relation, arel这种实体，逻辑体，工厂互相协同，松耦合，可扩展