對於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)
上面的代碼只執行一個查詢。 q1
和q2
不保留查詢的結果,而是他們的類是ActiveRecord::NamedScope::Scope
。
or
named_scope結合了這些查詢並將條件與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
回報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...>]
我相信大多數的這些例子在Rails 3中使用scope
會很好,儘管我還沒有嘗試過。
一點無恥的自我推銷 - 該功能可在fake_arel gem。
見我對同一個問題的回答[這裏](http://stackoverflow.com/a/40269481/1876622)。另外請注意類似的問題[這裏](http://stackoverflow.com/questions/37445203/)和[這裏](http://stackoverflow.com/questions/16381619/) – HeyZiko 2016-10-26 20:54:44