问题
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?
回答1:
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.
回答2:
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 .
来源:https://stackoverflow.com/questions/14219528/activerecord-anonymous-scope