How to combine multiple conditions in a find statement in Ruby on Rails

Posted on 12 April 2006

The best way for me to explain how to use multiple conditions is by example.

Basically I wanted to find 'departments' that match a 'permalink' and a particular 'category' - with both paramaters passed from the url.

My initial (and very wrong) code looked like this:


category = params[:category]
department = params[:department]

@departments = Department.find(:all, :conditions => ["permalink = ?", department])
@department = @departments.find(:all, :conditions => ["category = ?", category])

The first problem is that I was writing find :all to find a single record to go into @department. Using find :all will always return an array even if there is only one record found.

Secondly, I was performing a find on that array which simply doesn't work.

And thirdly, I was doing this in two steps when it would be far more efficient & simple to do it in one.

The final solution looked like this:


category = params[:category]
department = params[:department]

@department = Department.find(:first, :conditions => ["permalink = ? and category = ?", department, category])

find :all became find :first and the conditions statement was combined using the key word and. Easy when you know how!

Comments left...

  • again…nice example. thanks

    aaron at 21 Sep 07 at 21:23

  • Really good examples….am learning rails and have found good examples here

    sunil at 15 Sep 08 at 00:00

  • getting back into rails. this helped a bunch! thanks

    Tim at 11 Mar 09 at 09:06

Got something to say?