0xSina
0xSina

Reputation: 21573

ActiveRecord anonymous scope

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

scope = User.scoped

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?

Upvotes: 3

Views: 1214

Answers (2)

R Milushev
R Milushev

Reputation: 4315

I do not like to discourage you , but it's pretty sure , that in Rails 4 the method scoped is about to be deprecated . More interesting new features of the new version are discussed in this RailsCast .

Upvotes: 1

Jiří Pospíšil
Jiří Pospíšil

Reputation: 14412

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

scope = User.scoped

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

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.

Upvotes: 3

Related Questions