Rails3: combine scope with OR

前端 未结 3 1737
萌比男神i
萌比男神i 2020-12-09 12:00

I need to combine name scope with or operator... Something like:

class Product < ActiveRecord::Base
  belongs_to :client

  scope :name_a, where(\"product         


        
相关标签:
3条回答
  • 2020-12-09 12:37

    Heres a hack I would use to deal with that missing feature:

    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
    
    0 讨论(0)
  • 2020-12-09 12:37

    For Rails 3:

    Person.where(
      Person.where(name: "John").where(lastname: "Smith").where_values.join(' OR ')
    )
    
    0 讨论(0)
  • 2020-12-09 12:44

    From Arel documentation

    The OR operator is not yet supported. It will work like this: users.where(users[:name].eq('bob').or(users[:age].lt(25)))

    This RailsCast shows you how to use the .or operator. However, it works with Arel objects while you have instances of ActiveRecord::Relation. You can convert a relation to Arel using Product.name_a.arel, but now you have to figure out how to merge the conditions.

    0 讨论(0)
提交回复
热议问题