Alex Rivera | Logout

Using the .where method in Rails3

Asked 2011-01-07T16:45:00.530
14

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!

Edit
Report

1 Answer

1

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

answered 2012-09-05T01:27:00.307

Your Answer