Search code examples
sqlruby-on-railsrubyactiverecordarel

ActiveRecord Arel OR condition


How can you combine 2 different conditions using logical OR instead of AND?

NOTE: 2 conditions are generated as rails scopes and can't be easily changed into something like where("x or y") directly.

Simple example:

admins = User.where(:kind => :admin)
authors = User.where(:kind => :author)

It's easy to apply AND condition (which for this particular case is meaningless):

(admins.merge authors).to_sql
#=> select ... from ... where kind = 'admin' AND kind = 'author'

But how can you produce the following query having 2 different Arel relations already available?

#=> select ... from ... where kind = 'admin' OR kind = 'author'

It seems (according to Arel readme):

The OR operator is not yet supported

But I hope it doesn't apply here and expect to write something like:

(admins.or authors).to_sql

Solution

  • I'm a little late to the party, but here's the best suggestion I could come up with:

    admins = User.where(:kind => :admin)
    authors = User.where(:kind => :author)
    
    admins = admins.where_values.reduce(:and)
    authors = authors.where_values.reduce(:and)
    
    User.where(admins.or(authors)).to_sql
    # => "SELECT \"users\".* FROM \"users\"  WHERE ((\"users\".\"kind\" = 'admin' OR \"users\".\"kind\" = 'author'))"