Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord where or clause

I'm looking to write an ActiveRecord query and this is what I have below. Unfortunately you can't use OR like this. What's the best way to execute? category_ids is an array of integers.

.where(:"categories.id" => category_ids).or.where(:"category_relationships.category_id" => category_ids)
like image 682
bcackerman Avatar asked Sep 17 '13 22:09

bcackerman


Video Answer


2 Answers

One way is to revert to raw sql...

YourModel.where("categories.id IN ? OR category_relationships.category_id IN ?", category_ids, category_ids)
like image 131
Paul Sturgess Avatar answered Sep 25 '22 03:09

Paul Sturgess


Keep the SQL out of it and use ARel, like this:

.where(Category.arel_table[:id].in(category_ids).
  or(CategoryRelationship.arel_table[:category_id].in(category_ids))
like image 45
pdobb Avatar answered Sep 25 '22 03:09

pdobb