Rails3:将范围与OR结合

Pio*_*ioz 10 ruby activerecord scope ruby-on-rails-3

我需要将名称范围与运算符组合......类似于:

class Product < ActiveRecord::Base
  belongs_to :client

  scope :name_a, where("products.name = 'a'")
  scope :client_b, joins(:client).where("clients.name = 'b'")

  scope :name_a_or_b, name_a.or(client_b)  
end
Run Code Online (Sandbox Code Playgroud)

谢谢

Sim*_*tti 9

来自Arel文档

OR运营商尚不支持.它会像这样工作: users.where(users[:name].eq('bob').or(users[:age].lt(25)))

此RailsCast向您展示如何使用该.or运算符.但是,当您有实例时,它适用于Arel对象ActiveRecord::Relation.您可以将关系转换为Arel使用Product.name_a.arel,但现在您必须弄清楚如何合并条件.


Mac*_*rio 8

下面我会用来处理这个缺失的功能:

class Product < ActiveRecord::Base
  belongs_to :client

  class << self
    def name_a
      where("products.name = 'a'")
    end

    def client_b
      joins(:client).where("clients.name = 'b'")
    end

    def name_a_or_b
      clauses = [name_a, client_b].map do |relation| 
        clause = relation.arel.where_clauses.map { |clause| "(#{clause})" }.join(' AND ')
        "(#{clause})" 
      end.join(' OR ')

      where clauses
    end
  end
end
Run Code Online (Sandbox Code Playgroud)