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!

About Paul

Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.

Follow Paul on Twitter

Email: paulsturgess [at] gmail.com

Read more articles in the archive →

Comments...

  • 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

  • My following code not working, please guide, thanks.

    @params['body'].each do |contact|
    @c = Contact.find(:all, :conditions=> ["contact_id = ?", contact["contact_id"]])

    if @c.count > 0
    # update record
    else
    # insert record
    end
    end

    New Ruby at 16 Sep 10 at 23:46

  • This is a great example, thanks for sharing! Not only did it solve my problem I know understand more how ruby works.

    Kyle at 27 Mar 11 at 16:51

  • Thanks so much, was doing something different but :first saved my ass lol.

    Nick at 14 Aug 11 at 15:18

  • What about if you have hard query and don't know count of params?
    In Rails 3 I try:

    mass = [array of params]
    Model.find_by_sql(["SELECT ... <anything> = ? ... <anything> = ?", mass])

    but it's wrong. Have any ideas?

    Andrey at 16 Jan 12 at 15:45

Got something to say?