GN.
GN.

Reputation: 9839

How to use "or" on scopes

Trying to use or with scopes but it doesn't seem to work.

first_20 returns a relation, but when I use or, it complains that it returns an array, and throws an error. In most of the examples I can find, it is done exactly like I have it.

 scope :first_20, -> {
    first(20)
  }

 scope :starred, ->(list_or_urls) {
   where(url: list_or_urls)
 }

then later call it..

Org.first_20.or(starred(urls))

Getting a

ArgumentError (You have passed Array object to #or. Pass an ActiveRecord::Relation object instead.)
 Org.first_20.or(starred(list_or_urls))

How is it possible to use or with scopes?

Upvotes: 1

Views: 87

Answers (2)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

In first_20 scope, use the following query instead to return a ActiveRecord::Relation, first(20) returns an Array instead of relation, that's what your error tells

scope :first_20, -> { limit(20).order('id ASC') }

and, since starred is a class method, you need to call it on Org class.

Org.first_20.or(Org.starred(urls))

Hope that helps!

Upvotes: 4

Salil
Salil

Reputation: 47482

I agree with Rajdeep's answer it will definitely work, following is another way of doing it

scope :first_20_or_starred, ->(list_or_urls) { first_20.or(starred(list_or_urls)}

& then

Org.first_20_or_starred

Upvotes: 2

Related Questions