Rails3:将范围与OR结合

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

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 

谢谢

来自Arel文档

OR运算符尚不支持。 它的工作方式如下: users.where(users[:name].eq('bob').or(users[:age].lt(25)))

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

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

 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 

对于Rails 3:

 Person.where( Person.where(name: "John").where(lastname: "Smith").where_values.join(' OR ') )