Reputation: 5881
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
Upvotes: 5
Views: 3667
Reputation: 3915
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)))
Upvotes: 7
Reputation: 1124
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)))"
Upvotes: 0
Reputation: 4877
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])
Upvotes: 0