scope :active_without_owner, -> { where(active: true, role: 'owner') }
returns active users with role set to 'owner'.
I cannot figure out the syntax to return active users with role other than 'owner'.
I have tried
scope :active_without_owner, -> { where(active: true, not(role: 'owner')) }
and many many other combinations...
What is a named scope? A named scope is simply a class method inside of your model that always returns an active record association. Imagine this application: we have a database of shirts and we want to return all of the shirts that are red.
In Ruby on Rails, named scopes are similar to class methods (“class. method”) as opposed to instance methods (“class#method”). Named scopes are short code defined in a model and used to query Active Record database.
Scopes are used to assign complex ActiveRecord queries into customized methods using Ruby on Rails. Inside your models, you can define a scope as a new method that returns a lambda function for calling queries you're probably used to using inside your controllers.
A default scope is one which is automatically applied to your model.
This will work:
scope :active_without_owner, -> { where(active: true).where.not(role: 'owner')) }
I'd change it up a bit though and do this so you can reuse active
:
scope :active, -> { where(active: true) }
scope :active_with_owner, -> { active.where(role: 'owner') }
scope :active_without_owner, -> { active.where.not(role: 'owner')) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With