Neil
Neil

Reputation: 5178

Rails 4 scopes: grab all records between opposite scopes

I have the following model:

#models/foobar.rb
class Foobar < ActiveRecord::base
  scope :active, ->{where(active: true)}
  scope :inactive, ->{where(active: false)}
end

What I want to do is get an activerecord relation object that contains all the foobar records that are active. Then: I also want this same activerecord relation object to contain all foobar records that are inactive.

I don't think this does what I want it to:

# only returns the active records
Foobar.active.inactive

This wouldn't work either because it returns an array, not an activerecord relation object:

# returns an array not an activerecord relation object
Foobar.active + Foobar.inactive

How can I get the activerecord relation object to contain BOTH active and inactive foobar records? Better yet: Is there a way to create a scope that would do this for me?

Upvotes: 1

Views: 223

Answers (1)

Uday kumar das
Uday kumar das

Reputation: 1613

You can use this code:

scope :active_and_inactive, ->{where(active: [true,false])}

Through using Array you can pass multiple values for an attribute.

Upvotes: 2

Related Questions