作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想找到所有 Annotations
他们的 body 是:
Annotation.body_equals('?')
Annotation.body_like('[?]')
Annotation.body_equals('?').body_like('[?]')
OR
结合起来.
OR
if their argument is the same.例如,我可以这样做:
Annotation.body_equals_or_body_like('?')
最佳答案
我找不到任何简单的解决方案,但是这个问题引起了我的兴趣,所以我推出了自己的解决方案:
class ActiveRecord::Base
def self.or_scopes(*scopes)
# Cleanup input
scopes.map! do |scope|
scope = scope.respond_to?(:to_a) ? scope.to_a : [*scope]
scope.unshift(scope.shift.to_sym)
end
# Check for existence of scopes
scopes.each{|scope| raise ArgumentError, "invalid scope: #{scope.first}" unless self.scopes.has_key?(scope.first) }
conditions = scopes.map do |scope|
scope = self.scopes[scope.first].call(self, *scope[1..-1])
self.merge_conditions(scope.proxy_options[:conditions])
end
or_conditions = conditions.compact.join(" OR ")
merged_scopes = scopes.inject(self){|merged, scope| merged.scopes[scope.first].call(self, *scope[1..-1]) }
# We ignore other scope types but so does named_scopes
find_options = merged_scopes.scope(:find).merge(:conditions => or_conditions)
self.scoped(find_options)
end
end
class Person < ActiveRecord::Base
named_scope :men, :conditions => { :sex => 'M' }
named_scope :women, :conditions => { :sex => 'F' }
named_scope :children, :conditions => "age < 18"
named_scope :named, lambda{|name|
{ :conditions => { :name => name } }
}
end
Person.or_scopes(:women, :children)
Person.or_scopes(:women, :children).proxy_options
# => {:conditions=>"(`people`.`sex` = 'F') OR (age < 18)"}
Person.or_scopes(:women, [:named, 'Sue']).proxy_options
# => {:conditions=>"(`people`.`sex` = 'F') OR (`people`.`name` = 'Sue')"}
Annotation.or_scopes([:body_equals, '?'], [:body_like, '[?']).all
关于ruby-on-rails - 用 OR 组合两个命名范围(而不是 AND),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1482940/
我是一名优秀的程序员,十分优秀!