I had this bit of code using Squeel which worked perfectly:
.where {
[
entry[:imdb].presence && imdb == entry[:imdb],
entry[:asin].presence && asin == entry[:asin],
entry[:upc].presence && dvd_upc.upc == entry[:upc]
].compact.reduce(:|)
}
This would only create the query for the column if the entry[:variable_name]
was present, otherwise it would ignore it, very handy. Produced a query like the following:
"SELECT * FROM `table` WHERE ((`table`.`imdb` = 3026824 OR `table`.`asin` = 'B00E5PHTR8'))"
The great thing about this block is that I don't have to worry if the variable exists or not, if there is only 1 of the variables, the query will not use an OR
statement, etc. This is a lot harder to write with regular conditionals without making a big mess.
Also note that the whole point of this query is to not use column = NULL
when the variable is not present. Doing a search for column = NULL
will retrieve a bunch of useless and wrong hits.
However, Squeel is no longer maintained and has all sorts of failing issues with ActiveRecord 4.1 (and Rails 4.1 by extension). So the only choice I have if I want to use AR 4.1.1
and above is to get rid of all the squeel queries I had.
My question is, is this possible to do with an AR .where
block? I can't seem to find an answer other than no, it's not possible.