Scope provides elegant way to write commonly used query fragments and improve readability of your code. Scope returns a new collection Collection or taint the current Collection.
Let's get an example:
class Userinclude Clear::Modelprimary_keycolumn role : Stringcolumn role_level : Int32column email : Stringcolumn active : Boolscope :with_privileges do |level|where{ role.in?(%w(superadmin admin)) | (role_level > level) }endscope(:active){ where(active: true) }end# Later one:User.with_privileges(3).each do |x|puts "Admin #{x.id} - #{x.email}"end
Scope can be easily chained and you can pass argument to them too:
User.with_admin_privileges(4).active
Scope live both in Model::Collection
and Model
code space, meaning you may ignore Model.query
to start a new Collection but instead go straight to Model.scope
.