简体   繁体   中英

ActiveRecord OR Query in Arel

For simple queries, OR queries are possible in ActiveRecord like this:

Model.where({:category => "XYZ", :item_id => some_ids})
=>
table = Model.arel_table
Model.where(table[:category].eq("XYZ").or(table[:item_id].in(some_ids)))

The result is not very compact and clear. What if you have more complex queries, is it possible and useful to write the following ActiveRecord query in Arel as well?

Model.where(["(item_id = ? AND item_type = 'ABC') OR 
              (item_id IN (?) AND item_type = 'XYZ')",id,more_ids]).
      order("created_at DESC")

How about:

first_part = arel_table[:item_id].eq(id).and(arel_table[:item_type].eq('ABC'))
second_part = arel_table[:item_id].in(more_ids).and(arel_table[item_type].eq('XYZ'))    

Model.where(first_part.or(second_part)).order(created_at: :desc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM