Rails 2.x の場合、次の名前付きスコープを使用して OR をシミュレートできます。
__or_fn = lambda do |*scopes|
where = []
joins = []
includes = []
# for some reason, flatten is actually executing the scope
scopes = scopes[0] if scopes.size == 1
scopes.each do |s|
s = s.proxy_options
begin
where << merge_conditions(s[:conditions])
rescue NoMethodError
where << scopes[0].first.class.merge_conditions(s[:conditions])
end
joins << s[:joins] unless s[:joins].nil?
includes << s[:include] unless s[:include].nil?
end
scoped = self
scoped = scoped.includes(includes.uniq.flatten) unless includes.blank?
scoped = scoped.joins(joins.uniq.flatten) unless joins.blank?
scoped.where(where.join(" OR "))
end
named_scope :or, __or_fn
上記の例を使用して、この関数を使用しましょう。
q1 = Annotation.body_equals('?')
q2 = Annotation.body_like('[?]')
Annotation.or(q1,q2)
上記のコードは、1 つのクエリのみを実行します。 q1
クエリの結果を保持しq2
ません。むしろ、それらのクラスはActiveRecord::NamedScope::Scope
.
named_scope は、これらのor
クエリを結合し、条件を OR で結合します。
次の不自然な例のように、OR をネストすることもできます。
rabbits = Animal.rabbits
#<Animal id: 1 ...>
puppies = Animal.puppies
#<Animal id: 2 ...>
snakes = Animal.snakes
#<Animal id: 3 ...>
lizards = Animal.lizards
#<Animal id: 4 ...>
Animal.or(rabbits, puppies)
[#<Animal id: 1 ...>, #<Animal id: 2 ...>]
Animal.or(rabbits, puppies, snakes)
[#<Animal id: 1 ...>, #<Animal id: 2 ...>, #<Animal id: 3 ...>]
or
a 自体を返すためActiveRecord::NamedScope::Scope
、非常にクレイジーになる可能性があります。
# now let's get crazy
or1 = Animal.or(rabbits, puppies)
or2 = Animal.or(snakes, lizards)
Animal.or(or1, or2)
[#<Animal id: 1 ...>, #<Animal id: 2 ...>, #<Animal id: 3 ...>, #<Animal id: 4...>]
これらの例のほとんどはscope
、Rails 3 で s を使用しても問題なく動作すると思いますが、試したことはありません。
ちょっとした恥知らずな自己宣伝 - この機能はfake_arel gemで利用できます。