Search code examples
ruby-on-railsrubysearchkick

Multiple where clauses in rails searchkick


I have a very basic question about searchkick. What if you want you join multiple where statements in searchkick query using if statements. Much like query-builder

    @product = Product.all

    unless request.end_date.nil?
        @product = @product.search, where('created_at <= ?', request.end_date)
    end 

    unless request.max_price.nil?
        @product = @product.search, where('price <= ?', request.max_price)
    end 

    @product

The above code works fine if request has either end date or max_price. If it has both, it throws an error. Is there a way to construct or concatenate the two where statements. I cannot do

Product.search '*', where('created_at <= ?', request.end_date), where('price <= ?', request.max_price)

because if statement is important.


Solution

  • You should check docs of Searchkick, it has Or filter: https://github.com/ankane/searchkick

    where: {
      expires_at: {gt: Time.now}, # lt, gte, lte also available
      or: [
        [{in_stock: true}, {backordered: true}]
      ]
    }
    

    For your case, you can deal with it as below:

    conditions[:or] = [[]]
    unless request.end_date.nil?
        conditions[:or][0] += [{created_at: {lt: request.end_date}}]
    end 
    
    unless request.max_price.nil?
        conditions[:or][0] += [{price: {lt: request.max_price}}]
    end 
    Product.search '*', where: conditions