I need an SQL statement that check if one condition is satisfied:
SELECT * FROM my_table WHERE my_table.x=1 OR my_table.y=1
I want to do this the 'Rails 3' way. I was looking for something like:
Account.where(:id => 1).or.where(:id => 2)
I know that I can always fallback to sql or a conditions string. However, in my experience this often leads to chaos when combining scopes. What is the best way to do this?
Another related question, is how can describe relationship that depends on an OR condition. The only way I found:
has_many :my_thing, :class_name => "MyTable", :finder_sql => 'SELECT my_tables.* ' + 'FROM my_tables ' +
'WHERE my_tables.payer_id = #{id} OR my_tables.payee_id = #{id}'
However, these again breaks when used in combinations. IS there a better way to specify this?
With rails_or, you could do it like:
(It works in Rails 4 and 5, too.)
This will works in Rails 5, see rails master :
For Rails 3.0.4+:
Alternate syntax using Hash
This is particularly useful, when the value is compared with multiple columns. eg:
I've used the Squeel gem (https://github.com/ernie/squeel/) to do OR queries and it works beautifully.
It lets you write your query as
Account.where{(id == 1) | (id == 2)}
Account.where(id: [1,2])
no explanation needed.Those arel queries are unreadable to me.
What's wrong with a SQL string? In fact, the Rails guides exposes this way as the first way to make conditions in queries: http://guides.rubyonrails.org/active_record_querying.html#array-conditions
So, I bet for this way to do it as the "Rails way":
In my humble opinion, it's shorter and clearer.