Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

named scope with where and where.not

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...

like image 811
Olivier Severyns Avatar asked Dec 18 '14 21:12

Olivier Severyns


People also ask

What is named scope?

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.

What is a named scope in Rails?

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.

What is scope in ActiveRecord?

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.

What are default scopes in Rails?

A default scope is one which is automatically applied to your model.


1 Answers

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')) }
like image 198
Philip Hallstrom Avatar answered Sep 19 '22 07:09

Philip Hallstrom