5

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

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
vidur punj
  • 5,019
  • 4
  • 46
  • 65

3 Answers3

7

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)))
Kulbir Saini
  • 3,926
  • 1
  • 26
  • 34
0

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])
TomDunning
  • 4,829
  • 1
  • 26
  • 33
0

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)))" 
antiqe
  • 1,125
  • 8
  • 17
  • I am using this: a = Audio.scoped @audios=a.where(a.table[:album_id].in(@album_ids).or(a.table[:country_id].in(@country_ids))).to_sql ,but not abel to get desired output – vidur punj Aug 16 '12 at 08:01