Several articles that contain search queries

I have a very simple search question. What if you want you to join multiple operators in a search query using if statements. Same as 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 the request has either an end date or max_price. If it has both values, it throws an error. Is there a way to construct or combine two where statements. I can not do

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

because if statement is important.

+5
source share
1 answer

You have to check the Searchkick docs, it has either a filter: https://github.com/ankane/searchkick

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

In your case, you can deal with it as shown 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 
+4
source

Source: https://habr.com/ru/post/1207776/


All Articles