ActiveRecord::Relation是rails3中添加的。rails2中的finders, named_scope, with_scope 等用法,在rails3统一为一种Relation用法。

以下是返回ActiveRecord::Relation的方法:

bind
create_with
distinct
eager_load
extending
from
group
having
includes
joins
limit
lock
none
offset
order
preload
readonly
references
reorder
reverse_order
select
uniq
where

主要有以下优势:
1,惰性加载( Lazy Loading)
数据库并没有执行查询的动作,只有当真正使用这些数据的时候才会去查询数据库。
2,可以链式操作
Uers.where().where().order()....

一,实验验证惰性加载:
假设数据库中有一个posts表,表中有两个字段,id和title。
现在表中只有一条数据,id=1, title = old_name。
rails console
进入rails的控制台

p1 = Post.all
p2 = Post.order(:id)
p1.class #=> Array
p2.class #=> ActiveRecord::Relation

然后等待一会儿,去数据库中,将"old_name"改为"new_name"。这样的话,因为Post.all是立即加载数据,Post.order(:id)是惰性加载数据,所以改了

title之后,p1和p2的值应该是不相同的。

p1[0]

=> #<Post id: 1, title: "old_name", created_at: "2014-05-08 00:45:27", updated_at: "2014-05-08 00:45:27">

p2[0]
=> #<Post id: 1, title: "old_name", created_at: "2014-05-08 00:45:27", updated_at: "2014-05-08 00:45:27">

发现p1和p2的结果是相同的,Post.order(:id)并没有惰性加载数据,为什么呢?

原因是在rails的控制台中,会打印出语句的返回结果,也就使用了这些数据,所以这么修改p1和p2两行为:

p1 = Post.all;nil
p2 = Post.order(:id);nil

这样重新执行上边的流程,结果如下:

p1[0]

=> #<Post id: 1, title: "old_name", created_at: "2014-05-08 00:45:27", updated_at: "2014-05-08 00:45:27">

p2[0]
=> #<Post id: 1, title: "new_name", created_at: "2014-05-08 00:45:27", updated_at: "2014-05-08 00:45:27">

实验验证链式操作:
操作Relation实例的时候,会查询数据库。进入 activerecord-3.2.13\lib\active_record\relation.rb,找到inspect方法的定义:

def inspect
to_a.inspect
end

可以看出,调用先将Relation实例转换成数据,然后再将其inspect。

p2.inspoect
=> "[#<Post id: 1, title: \"new_name\", created_at: \"2014-05-08 00:45:27\", updated_at: \"2014-05-08 00:45:27\">]"

将inspect方法注释掉,然后看Relation实例中的内容

"#<ActiveRecord::Relation:0x463cbf0
@table=#<Arel::Table:0x4626e88 @name=\"posts\",
@engine=Post(id: integer, title: string, body: text, created_at: datetime, updated_at: datetime),
@columns=nil,
@aliases=[],
@table_alias=nil,
@primary_key=nil>,
@klass=Post(id: integer, title: string, body: text, created_at: datetime, updated_at: datetime),
@implicit_readonly=nil,
.......
@group_values=[],
@order_values=[:id],
@joins_values=[],
@where_values=[],
@having_values=[],
.......
@records=[]>"

可以看出Relation对象中根本就没有存储数据库中的内容,因为使用了order(:id)方法,所以@order_values=[:id]存储了查询信息。
对以Post.where("id = 1").order(:id),相应的Relation实例中值为:
@order_values=[:id],
@where_values=["id = 1"]

每一次链式操作都会在Relation中添加对应的查询条件,在使用的时候才去生成SQL语句,查询数据库。

总结:

知道了ActiveRecord::Relation的内部组织结构就非常好理解惰性加载和链式操作了,Relation让数据库操作更加优雅!

理解ruby on rails中的ActiveRecord::Relation的更多相关文章

  1. 【转】Ruby on Rails中select使用方法

    在Ruby on Rails中真的有一堆Select helper可以用,我们经常容易混淆.常见的有三个..select, select_tag, collection_select(其余的什么sel ...

  2. ruby on rails 中render的

    Ruby rails页面跳转代码如下: 1.render(:text => string) 2.render(:inline => string, [:type => "r ...

  3. Ruby on Rails中的Rake教程(Rake如何把我灌醉!)

    下面是我们使用Rake任务的例子: 1.给列表中的用户发送邮件 2.每晚数据的计算和报告 3.过期或重新生成缓存 4.备份数据和svn版本(how's this : subversion reposi ...

  4. ruby on rails 中render的使用

    最近写ror,因为比较菜,很多东西不知道,只能看一点查一点了 render 先上点搜集的常用方式 render :action => "long_goal", :layout ...

  5. json格式在ruby和rails中的注意事项

    #虚拟网络拓扑的json数据 def topodata #@vnic = Vnic.all #flash.now[:notice] = 'Message sent!' #flash.now[:aler ...

  6. Ruby on Rails 中你使用了Kaminari 后,千万不要再引入will_pagination 这个Gem 了

    今日做开发的时候发现的这个问题 发现无论怎样配置都不能使用Kaminari 的Per 这个功能,分页大小也固定在了30 最开始还以为是Ransack 这个Gem 影响的,上网搜了很久发现没有 最后仔细 ...

  7. ruby on rails模拟HTTP请求错误发生:end of file reached

    在文章 Ruby On Rails中REST API使用演示样例--基于云平台+云服务打造自己的在线翻译工具 中,利用ruby的Net::HTTP发起http请求訪问IBM Bluemix上的sour ...

  8. 通过Ruby On Rails 框架来更好的理解MVC框架

    通过Ruby On Rails 框架来更好的理解MVC框架   1.背景    因为我在学习软件工程课程的时候,对于 MVC 框架理解不太深入,只是在理论层面上掌握,但是不知道如何在开发中使用 MVC ...

  9. ubuntu 14.04中安装 ruby on rails 环境

    环境:在win7 上Vmware虚拟机环境中安装的ubuntu 14.04 1. bundle install 时,报json错误可以看出是在安装nokogiri时遇到了问题,此时执行 sudo ap ...

随机推荐

  1. Missing artifact com.sun:tools:jar:1.5.0:system 补充

    转自:http://blog.csdn.net/sweblish/article/details/6662586 解决方案一: 原来,是${java.home}在作怪,eclipse 没有使用 JAV ...

  2. android 操作sqlite的一点小技巧

    1.android 在sqlite插入数据时,是非常耗时的操作,原因是sqlite缺省会为每个插入操作开启一个事务,当数量变多的时候,自然时间就变得很慢,这时候可以考虑在插入等操作时先开启一个事务,再 ...

  3. 置换贴图 Displacement Mapping

    视差贴图和法线贴图都是使用特定的手段来达到欺骗视觉的目的,让人以为物体的表面是凹凸起伏的.而置换贴图却是真的将模型的顶点进行偏移,在原本的平面上创造出凹凸的效果.既然是对顶点进行偏移,那么就需要模型有 ...

  4. FFTW库在VS 2010中的使用方法

    一.FFTW库简介(from百度百科)       FFTW ( the Faster Fourier Transform in the West) 是一个快速计算离散傅里叶变换的标准C语言程序集,其 ...

  5. The str method

    __str__ is a special method name, like __init__, that is supposed to return a string representation ...

  6. linux中ll和du的区别

    首先,明确一个概念,linux中目录其实也是一个文件,它存储了一张表,该表就是该目录文件下,所有文件名和inode的映射关系. 其中inode和数据块block的关系http://c.bianchen ...

  7. 操作笔记:linux下安装ftp

    1,安装ftp [root@iZ945sgm0ugZ ~]# yum install vsftpd 安装成功的信息: [root@iZ945sgm0ugZ ~]# yum install vsftpd ...

  8. oracle中的针对该库的表

    ALL_TAB_COLUMNS:所有用户的表字段 USER_TAB_COMMENTS:当前用户的所有表备注 USER_COL_COMMENTS:当前用户的所有列备注 USER_TAB_COLUMNS: ...

  9. [drp 5] pageModel的建立,实现分页查询

    导读:之前做的分页,一直都是用的easy--UI分页,然后没有系统的整理过,就是知道传几个参数,然后云云.这次,从头到尾总结一下,了了我的这桩心愿.人事系统的重定向工作,一直刺激着我一定要总结总结这个 ...

  10. badge ionic tab

    我需要在tab上动态显示 badge badge="badges.carts" badge-style="badge-assertive" 将这段代码 放在了 ...