Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching in where in rails with or clause for [IN]

I am using this query in rails

here: @album_ids , @country_ids are Arrays

@audios= Audio.where({:album_id => @album_ids, :country_id => @country_ids})
It produces following SQL:

 Audio Load (0.3ms)  SELECT `audios`.* FROM `audios` WHERE `audios`.`album_id` IN (1, 2) AND `audios`.`country_id` IN (1, 2)

But I want the query to be produced as:

 Audio Load (0.3ms)  SELECT `audios`.* FROM `audios` WHERE `audios`.`album_id` IN (1, 2) OR `audios`.`country_id` IN (1, 2) 

OR Rather than AND

Thanks in advance

like image 823
vidur punj Avatar asked Aug 16 '12 07:08

vidur punj


1 Answers

For Rails 3 (using AREL),

at = Audio.arel_table
audios = Audio.where(at[:album_id].in(@album_ids).or(at[:country_id].in(@country_ids)))

# Audio Load (0.3ms)  SELECT `audios`.* FROM `audios` WHERE ((`audios`.`album_id` IN (1, 2) OR `audios`.`country_id` IN (1, 2)))
like image 181
Kulbir Saini Avatar answered Nov 14 '22 21:11

Kulbir Saini