How to combine multiple conditions in a find statement in Ruby on Rails
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!
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
2 comments made
again…nice example. thanks
Really good examples….am learning rails and have found good examples here
Got something to say?