Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the .where method in Rails3

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!

like image 581
Elliot Avatar asked Jan 07 '11 16:01

Elliot


3 Answers

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).

like image 183
cam Avatar answered Nov 18 '22 11:11

cam


Look at MetaWhere, https://github.com/ernie/meta_where - this allows that sort of thing quite neatly :)

like image 23
Steve Hill Avatar answered Nov 18 '22 12:11

Steve Hill


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

like image 3
Mortice Avatar answered Nov 18 '22 12:11

Mortice