views:

299

answers:

3

this works:

ids = [1,2]
varietals = Varietal.find(:all, :conditions => [ "id IN (?)",ids])

But what I want to do is that plus have a condition of: deleted => false

varietals = Varietal.find(:all, :conditions =>{ :deleted => false})

any ideas?

am i going to have to use find_by_sql?

+2  A: 

You can do it a few ways, but this is the most straight forward:

varietals = Varietal.find( [1,2], :conditions => { :deleted => false })

You can see in the docs that the first parameter of find can take an integer or an array.

Doug Neiner
is this approach sql injection safe? It looks like AR doesn't do prepared statements anyway I write it, so not sure how AR prevents sql injection
phil swenson
Yes, this statement is SQL injection safe. It only allows an integer or an array of integers nothing more or less. As long as you follow the proper conventions for calling your AR finds, your queries will be safe. (i.e. don't do: `:conditions => 'deleted = #{@deleted}'` instead do `:conditions => {:deleted => @deleted}` or something similar.
Doug Neiner
+1  A: 
ids = [1,2]
varietals = Varietal.find(:all, :conditions => {:id => ids, :deleted => false})

This should work, haven't tested it though.

From the docs:

An array may be used in the hash to use the SQL IN operator:

Student.find(:all, :conditions => { :grade => [9,11,12] })
this workds too, but the one from Doug Neiner is more concise
phil swenson
it is and for this case may be the better choice. but you should be thankful that you now know how to group multiple conditions in a hash! ;)
i am. thanks :)
phil swenson
+2  A: 

I would handle this with a named_scope to communicate intent and foster re-use:

named_scope :undeleted,
            :conditions => { :deleted => false }

Then you can simply use:

varietals = Varietal.undeleted.find([1,2])
Toby Hede