Rails return model subsets, a = false always, a = true sometimes

11 Views Asked by At

Assume there is a model, Users and Users has the field admin (just an example).

The query must always return all Users where admin == false but only when asked to do so, to also return all Users where admin == true, but in one single DB request.

so the return subsets might be:

where A is admin == false

where B is admin == true

Return A OR A ∪ B

1

There are 1 best solutions below

1
On BEST ANSWER

Something like this should work:

scope :not_admins, -> { where(admin: false) } // this is A
scope :admins, -> { where(admin: true) } // this is B

def self.example(include_admins = false)
  if include_admins
    self.not_admins.or(self.admins) // A U B
  else
    self.not_admins // A
  end
end

then you just call User.example() or User.example(true) depending on if you want A or A U B