Rails: How to chain scope queries with OR instead of AND?

Rails: How to chain scope queries with OR instead of AND?

Asked on January 11, 2019 in Ruby on Rails.
Add Comment


  • 3 Answer(s)

    New AR3 syntax: 

    Person.where('name=? OR lastname=?', 'John', 'Smith')
    

    Answered on January 11, 2019.
    Add Comment

    Using ARel:

    t = Person.arel_table
     
    results = Person.where(
      t[:name].eq("John").
      or(t[:lastname].eq("Smith"))
    )
    
    Answered on January 11, 2019.
    Add Comment

    Update for Rails4 is requires no 3rd party gems,

    a = Person.where(name: "John") # or any scope
    b = Person.where(lastname: "Smith") # or any scope
    Person.where([a, b].map{|s| s.arel.constraints.reduce(:and) }.reduce(:or))\
    .tap {|sc| sc.bind_values = [a, b].map(&:bind_values) }
    

    previous command: 

     Person.where(
       Person.where(:name => "John").where(:lastname => "Smith")
         .where_values.reduce(:or)
    )
    

    Answered on January 11, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.