ActiveRecord anonymous scope

你说的曾经没有我的故事 提交于 2019-12-24 05:18:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!