2014-05-19 30 views
1

對於簡單的查詢,或查詢中的ActiveRecord可能是這樣的:的ActiveRecord或查詢在阿雷爾

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

結果是不是很緊湊,清晰。如果您有更復雜的查詢, 在Arel中編寫以下ActiveRecord查詢是否可行並且有用?

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

看看https://github.com/oelmekki/activerecord_any_of – apneadiving

回答

2

如何:

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)