Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I couldn't find any simple solutions, but this problem intrigued me, so I rolled my own solution:</p> <pre><code>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 =&gt; or_conditions) self.scoped(find_options) end end </code></pre> <p>Consider the following setup:</p> <pre><code>class Person &lt; ActiveRecord::Base named_scope :men, :conditions =&gt; { :sex =&gt; 'M' } named_scope :women, :conditions =&gt; { :sex =&gt; 'F' } named_scope :children, :conditions =&gt; "age &lt; 18" named_scope :named, lambda{|name| { :conditions =&gt; { :name =&gt; name } } } end </code></pre> <p>You call it with the names of a series of scopes as such:</p> <pre><code>Person.or_scopes(:women, :children) </code></pre> <p>This returns a scope like this:</p> <pre><code>Person.or_scopes(:women, :children).proxy_options # =&gt; {:conditions=&gt;"(`people`.`sex` = 'F') OR (age &lt; 18)"} </code></pre> <p>You can also call it with an array of arrays when the scope requires parameters:</p> <pre><code>Person.or_scopes(:women, [:named, 'Sue']).proxy_options # =&gt; {:conditions=&gt;"(`people`.`sex` = 'F') OR (`people`.`name` = 'Sue')"} </code></pre> <p>In your case Horace, you could use the following:</p> <pre><code>Annotation.or_scopes([:body_equals, '?'], [:body_like, '[?']).all </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload