Search code examples
ruby-on-railsruby-on-rails-3activerecord

Or & and in Rails ActiveRecord where clause


I'm using Rails 3.2 and I've got a database table in which I want to find all the rows that match the following criteria:

a = true and b = true and ( 0< c <1 or d=1), a, b, c, d are columns.

Can I have something like:

 Route.where(:a => true,
             :b => true,
             :c => 0..1 OR :d=1
             ).all          

Solution

  • I may be wrong, but I don't think you could form that query using the Arel-based where function; you'd need to form up the database query string yourself.

    Assuming you're using SQLite or Postgres:

    Route.where("a = true and b = true and ((c > 0 and c < 1) or d = 1)").all
    

    I haven't tested this code, but I suspect that might do the job for you. Note this is less 'portable' code; if you change the database you're using the query may break.