I've just started using the .where method, and I'm a little bit confused about how to fully utilize it.
I'd like to do something like:
@books = Book.where(:author_id => 1 || 2)
clearly I know that doesn't work, but I'm trying to demonstrate that I want some extra logic here. some "or" "and" "does not equal" etc.
Any ideas for where I can research this? I was looking in the rails API but I didnt see anything that was that helpful.
Thanks!
1 || 2
won't work because that expression is evaluated before the function call (it evaluates to 1, so it should be equivalent to Book.where(:author_id => 1)
. I would do:
@books = Book.where(:author_id => [1, 2])
The generated SQL would be WHERE author_id IN (1, 2)
.
Look at MetaWhere, https://github.com/ernie/meta_where - this allows that sort of thing quite neatly :)
Looking at the source (no decent documentation!), you can pass through SQL, which can be parameterized like the sql for :conditions, etc., so you can do something like:
@books = Book.where("author_id = 1 OR author_id = 2")
Not ideal to drop down to raw SQL, but I can't see a more elegant way to do it using the where method.
Source and absence of documentation here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With