Elliot
Elliot

Reputation: 13845

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!

Upvotes: 14

Views: 9462

Answers (4)

jpgeek
jpgeek

Reputation: 5291

It sounds like you might want to look at Arel for more complex things. It is already built into Rails 3 (AR uses it internally).

book = Book.arel_table
# range
Book.where(book[:author_id].gt(0).and(book[:author_id].lt(3))

#or
Book.where(b[:author_id].eq(0).or(t[:author_id].eq(3).order(:first_name))

#joins
book.join(authors).on(book[:author_id].eq(author[:id])).
    where(book[:title].matches 'hokum n stuff')

Also group by, aggregation and much more. The drawback is that the documentation is sparse. docs

tests

Upvotes: 1

cam
cam

Reputation: 14222

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

Upvotes: 26

Steve Hill
Steve Hill

Reputation: 2321

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

Upvotes: 4

Mortice
Mortice

Reputation: 221

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

Upvotes: 3

Related Questions