Scopes in Rails 3
Scopes have become much more useful in Ruby on Rails 3 with the adoption of Arel into ActiveRecord. The first and most obvious benefit related to scopes is that everything is scoped! That means you no longer have to use find(…) on an ActiveRecord model and have a query immediately be executed. You can actually build queries up and only execute them when you use them. For example:
In Rails 2.x the find method worked like this:
This would then execute the query and find all users with age 33. In Rails 3.x this is much simpler:
Not only is this more readable since you don’t have to put your entire query into a single function call, but the main difference between these two commands is that the second doesn’t execute a query. You actually have to call .all, .count, .each or .first to get the query to execute. What’s great about that? Well, it means you can chain conditions together before you execute them:
This really shines when you combine it with scopes. For instance, if we want to simplify the above code, we can do the following:
Isn’t that just awesome!? Not only is the code easier to read and understand, but it’s re-usable and scoped! Here’s one more example: