Clear ORM
Search…
Scopes
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:
1
class User
2
include Clear::Model
3
4
primary_key
5
6
column role : String
7
column role_level : Int32
8
column email : String
9
column active : Bool
10
11
scope :with_privileges do |level|
12
where{ role.in?(%w(superadmin admin)) | (role_level > level) }
13
end
14
scope(:active){ where(active: true) }
15
end
16
17
# Later one:
18
User.with_privileges(3).each do |x|
19
puts "Admin #{x.id} - #{x.email}"
20
end
Copied!
Scope can be easily chained and you can pass argument to them too:
1
User.with_admin_privileges(4).active
Copied!
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.
Last modified 2yr ago
Copy link