views:

40

answers:

2

Is there a way to make ActiveRecord write 'WHERE (a,b) in ((1,2),(3,4))' using AR finders.

I would think

Widget.find(:all, :conditions => ['(a,b) in (?)', [[1,2][3,4]]])

but the inner arrays get converted to YAML?!?! Right now I'm using find_by_sql. Is there a better way to write this?

A: 

Depending on how dynamic you need this to be, you could always do it in a string, like this:

Widget.all(:conditions => ["(a,b) in ((1,2), (3,4))"])

This at least saves you from doing the find_by_sql call. Could you also use an OR operator to split up the two arrays?

Josh
+2  A: 

You can do this:

Widget.all(:conditions => ["(a,b) in ((?),(?))", [1,2], [3,4]])

Although that's not ideal if you have a variable number of values. Sounds like a good opportunity for a patch to ActiveRecord!

Update: a kludge for a variable number of values. Still better than doing find_by_sql...but you're right, it should be supported by AR natively.

values = [[1,2],[3,4]]
Widget.all(:conditions => ["(a,b) in (#{Array.new(values.length,'(?)').join(',')})", *values])
Brad G.
Yup. I have a variable number of args so I have a map/sanitize/join sql writer. It works but I agree that this is something the framework should do.
Samuel Danielson