I want to generate the following SQL query using ActiveRecord for Rails:
SELECT * FROM users WHERE (((1 IS NULL) OR (10 > 20)) AND (2 IS NULL OR (10 > 1)));
So I wrote the following scope:
where('1 IS NULL')
.or(where('10 > 20'))
.where('2 IS NULL')
.or(where('10 > 1'))
However I am getting a slightly different query:
SELECT * FROM users WHERE (((1 IS NULL) OR (10 > 20)) AND 2 IS NULL OR (10 > 1));
Note that the first has no brackets surrounding everything after AND
whilst the first does. This effects the results I get (the first query evaluates to false whilst the second true).
How can I write the second query using ActiveRecord?
This question seems very similar: How to properly add brackets to SQL queries with 'or' and 'and' clauses by using Arel? Arel is now part of Rails so any answer there should be relevant.
The difference is both queries are the same which lead to a discussion about how to make it clearer, and secondly it was for an older version of Rails so the answers don't seem to work.
I also don't want to need a new gem for this, I think ActiveRecord should be able to handle this.
Edit:
I ended up writing it like this:
where("(1 IS NULL OR 10 > 20) AND (2 IS NULL OR 10 > 1)")
but now I'm just going around ActiveRecord, I was hoping to do it with ActiveRecord