Raylar 2.x için, YA simüle aşağıdaki adlandırılmış kapsamı kullanabilirsiniz:
__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
en yukarıdaki örneği kullanarak bu işlevi kullanalım.
q1 = Annotation.body_equals('?')
q2 = Annotation.body_like('[?]')
Annotation.or(q1,q2)
Yukarıdaki kod yalnızca bir sorgu yürütür. q1
ve q2
sorgunun sonuçlarını tutmayın, bunun yerine, sınıfları ActiveRecord::NamedScope::Scope
olur.
named_scope or
bu sorguları birleştirir ve koşulları bir OR ile birleştirir.
Ayrıca yuva OO'lar gibi bu yapmacık örnekte olabilir:
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
Çünkü getiri bir ActiveRecord::NamedScope::Scope
kendisi, gerçekten Çıldırabiliriz:
# 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...>]
İnanıyorum ki bu örneklerin çoğunda denemedim rağmen Rails 3 scope
s kullanarak iyi çalışır.
A Ufak olmayan kişisel tanıtım - Bu işlev fake_arel gem numaralı telefondan edinilebilir.
bakın Aynı soruya cevabım [işte] (http://stackoverflow.com/a/40269481/1876622). Ayrıca benzer sorulara [burada] dikkat edin (http://stackoverflow.com/questions/37445203/) ve [here] (http://stackoverflow.com/questions/16381619/) – HeyZiko