Rails 3中ActiveRecord的方法链,引擎盖下 [英] Rails 3 ActiveRecord method chaining, under the hood

查看:129
本文介绍了Rails 3中ActiveRecord的方法链,引擎盖下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你建立涉及多个方法链接,如

Let's say you build a query involving multiple method chaining, such as

Post.where('id > 10').limit(20).order('id asc').except(:order)

我不知道幕后发生了什么? presumably链的每个部分将有助于建立一个SQL SELECT,一旦链条完整的语句被执行,创建等它是如何知道的模型,其中链的末端是?是否每个方法返回一个ActiveRecord ::关系这将创建一个SQL片段?

I'm wondering what happens behind the scene? Presumably each part of the chain will help build a SQL SELECT and once the chain is 'complete' the statement is executed, models created etc. How does it 'know' where the end of the chain is? Does each method return an ActiveRecord::Relation which creates a SQL fragment?

推荐答案

您是正确的,这些回报的<一个href="http://api.rubyonrails.org/classes/ActiveRecord/Relation.html"><$c$c>ActiveRecord::Relation.每个方法调用是建立在它被要求(除了第一个,这显然没有任何关系的基础上,因为它不叫上关系)的关系,并返回。

You are correct, each of these returns an ActiveRecord::Relation. Each method call builds upon the relation it was called on (except the first, which obviously has nothing to build on, as it was not called on a relation), and returns that.

据知道里的链的末端是因为查询没有实际执行,直到你尝试和操作/访问数据,并在这样做有(通常是隐含地)被称为<一个href="http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-to_a"><$c$c>to_a它运行<一href="https://github.com/rails/rails/blob/v4.0.2/activerecord/lib/active_record/relation.rb#L581-L603"><$c$c>exec_queries.

It "knows" where the end of the chain is because the query is not actually executed till you try and manipulate/access the data, and in doing so have (usually implicitly) called to_a which runs exec_queries.

这篇关于Rails 3中ActiveRecord的方法链,引擎盖下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆