ActiveRecord 匿名作用域 [英] ActiveRecord anonymous scope

查看:29
本文介绍了ActiveRecord 匿名作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过观看 RailsCast 视频 了解匿名范围.当我自己尝试时,它似乎是这样的:

I am learning about anonymous scope from watch RailsCast video. When I try it myself, it seems like the statement:

scope = User.scoped

立即用SQL语句查询数据库:

immediately queries the DB with SQL statement:

User Load (3.2ms)  SELECT `users`.* FROM `users` 

在我什至有机会链接条件之前.这显然是非常低效的,而且视频中的作者这样做时不会发生这种情况.我错过了什么?

Before I even have a chance to chain conditions. This is obviously very inefficient and it's not happening when the author in the video does it. What am i missing?

此外,作用域在什么时候知道我已完成链接条件,是时候执行查询了?

Also, at what point does the scope know that I am done chaining conditions and it's time to perform the query?

推荐答案

您是否在控制台中尝试此操作?问题是如果你输入:

Are you trying this in the console? The problem is that if you type:

scope = User.scoped

console 尝试检查最后一条语句并触发查询.为了避免这种情况,只需在最后返回一些内容:

The console tries to inspect the last statement and triggers the query. To avoid that, simply return something at the end:

scope = User.scoped; nil

这样 console 会检查 nil 并且你的 scope 变量没有任何反应.这在实际代码中不会成为问题,因为在您定义它之后没有人会立即尝试检查它.

This way the console inspects nil and nothing happens to your scope variable. This won't be a problem in the actual code since nobody will try to inspect it right after you define it.

这篇关于ActiveRecord 匿名作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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