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

Is there a way to get ActiveRecord to 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 internal arrays are converted to YAML?!?! I am currently using find_by_sql. Is there a better way to write this?

+3
source share
2 answers

You can do it:

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

Although this is not ideal if you have a variable number of values. Sounds good for a patch for ActiveRecord!

Update: kludge for a variable number of values. 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])
+2

, , , :

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

, , find_by_sql. OR ?

0

Source: https://habr.com/ru/post/1731689/


All Articles