Question

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

Was it helpful?

Solution

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)))

OTHER TIPS

Where clauses will always create an AND, either change it to a 2 liner:

@audios  = Audio.where({:album_id => @album_ids})
@audios += Audio.where({:country_id => @country_ids})

since rails3 doesn't call the searches inline, but instead compiles the query it should do it as one query.

OR:

@audios= Audio.where(["album_id IN (?) OR country_id IN (?)", @album_ids, @country_ids])

Try this method

a = Report.scoped
a.where(
  a.table[:id].in([1,2,3])
    .or( 
      a.table[:model_id].in([3,4,5])
    )
  ).to_sql
=> "SELECT `reports`.* FROM `reports`  WHERE ((`reports`.`id` IN (1, 2, 3) OR `reports`.`model_id` IN (3, 4, 5)))" 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top