Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP


Scope ActiveRecord queries with OR instead of AND #5545

emilecantin opened this Issue · 9 comments

6 participants


ActiveRecord should provide a way to chain scopes using OR, as asked here:

Reproduced here for your convenience:

I'm using Rails3, ActiveRecord

Just wondering how can I chain the scopes with OR statements rather than AND.


Person.where(:name => "John").where(:lastname => "Smith")
That normally returns name = 'John' AND lastname = 'Smith', but I'd like:

name = 'John' OR lastname = 'Smith'

I have some named scopes defined (for a search functionality), and I would like to be able to reuse them for a keyword search.


where(:name => ["John", "Smith"]) should solve your problem.


[4] pry(main)> Group.where(:name => ['Vanguard Cadets', 'Santa Clara Vanguard'])
  Group Load (16.0ms)  SELECT "groups".* FROM "groups" WHERE "groups"."name" IN ('Vanguard Cadets', 'Santa Clara Vanguard')

Thanks, but I think I haven't made myself clear. The above was an example from the internet, not my actual problem. Here it is: I have a Location model like this:

class Location < ActiveRecord::Base
    belongs_to :city

    def self.search_by_city (query)

    def self.search_by_description (query)
      where("locations.description LIKE ?", "%#{query}%")


With that, I can do Location.search_by_city "Seattle", Location.search_by_description "College", or even Location.search_by_city("Seattle").search_by_description("College"), which ANDs the two conditions. I want to be able to OR them without rewriting them each time. (DRY principle)


@bobbytables Your solution is great when you're comparing a single field against multiple values. Unfortunately, that's not the issue here. :-)

I've actually wanted something to abstract the SQL away, as well. ActiveRecord leaves a bit too much SQL in the hands of the user.


Ok, I will close the issue. I am perfectly willing to add the feature myself, but I do not know where to start.

Anyone willing to help me, or at least point me in the right direction?


You can do this if you jump down a level into arel. Something like

people = Person.arel_table

I do agree it would be nice to be able to do this without diving into arel however.


@emilecantin email? or dm me.


@kurko emilecantin AT


+1 for this.

I wrote a quick attempt here:

though it uses the syntax:
Jobship.includes(:job).or(Jobship.accepted, Jobship.declined).count

whereas it might be better like this:


Anyone interested in helping me work on this further?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.