Rails Scopes: Create Faster, Cleaner Queries
With the use of scopes
, a developer can create a fast query and add additional methods like pluck
that would otherwise throw an error.
Why use Scopes?
Scopes allow a developer to create reusable code instead of a method in the controller. Scopes also return an ActiveRecord::Relation
object, opening the door for combining multiple scopes.
Let's look at one example where scopes are better:
def member_ids member_emails = ['john.smith@example.com', 'm.jackson@example.com', 'bob.smith@exmple.com'] Account.where(email: member_emails) end
How to Create:
scopes
are created inside a method. While not required, adding additional arguments is possible.
Ex:
scope :name_for_method, →(arguments NOT required) {query is inserted here!}
# Grab all users with a certain role (roles is an array) scope :admin, { where('? = ANY(roles)', 'Admin') }
This will allow using the method globally for the class. A class in Ruby is a controller. It also has methods.
```ruby
@group.announcements.manager_all_messages(current_user)
```
Or grab all accounts with a certain role. This is created inside the method file for your Ruby class.
def admin Account.admin.pluck(:id) end
Conclusion:
Scopes provide cleaner code and remove the need for multiple class methods. They also allow combining multiple scopes and do not contain overly complicated logic.