Skip to content

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 all my departments that match a permalink passed from the url. The department must also match a particular category, also passed through the url.

My initial 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. When using find :all would return a hash (array) even if there is only one result row.

Secondly, I was incorrectly, and unecessarily, using Enumerable#find on @departments.

Enumerable#find requires 0 or 1 argument and 1 block, it doesn't work on arrays.

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!

View the snippets archive ››

2 comments made

aaron commented on 21 Sep 07 at 21:23

again…nice example. thanks

sunil commented on 15 Sep 08 at 00:00

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

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com