Ruby scopes are special active record methods to run database queries. Scopes enables us to define reusable query fragments which can then be chained together to define complex and expressive queries.
Scopes are cleaner in code because of their syntax. Scopes are used exactly for one thing, so we know what it means when we see one.
Scopes are not mixed with other methods, so they are easier to see.
class Awesome < ApplicationRecord
scope :tada, ~> { where(like_grapes: true) }
end
They are cleaner than class methods.
To define a simple scope, we use the scope method inside the class, passing the query we would like to pass.
Comments
Informative by Suraj Pathak about 1 month ago
Great by Ankeet Karki about 1 month ago
Nice article by Bibhushan Paudel about 2 months ago
Nice one . by Aakash Dawadi about 2 months ago