Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 502
0xSina Avatar asked Dec 05 '25 14:12

0xSina


2 Answers

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.

like image 148
Jiří Pospíšil Avatar answered Dec 07 '25 03:12

Jiří Pospíšil


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 .

like image 29
R Milushev Avatar answered Dec 07 '25 04:12

R Milushev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!