0

I have the following array of price ranges how can I perform a query to find the price range between these using and operator

This is the array I have

["0-1000", "5001_15000", "15001_25000"]

Whether this is the only way I have to perform else is ther any methods to perform such filter

select * from posts where price between 0 and 1000 and price between 5001 and 15000

Edit-1

As your said I tried in my console

a = [[0,1000],[5001 ,15000], [15001, 25000]]

(a[0].first..a[0].last)

This gives 0..1000 and when I try

(a[0].first..a[0].last and a[1].first..a[1].last)

It shows only 5001..15000 can you explain it please.

Edit-2

Only this works how can I add more values

Post.where(price: a[0].first..a[0].last)
Chris Travers
  • 25,424
  • 6
  • 65
  • 182
kndwsu
  • 371
  • 1
  • 8
  • 21

2 Answers2

0

I'd start adjusting your price range array. From:

["0-1000", "5001_15000", "15001_25000"]

to

a = [[0,1000],[5001 ,15000], [15001, 25000]]

This will give you access to first and last price range bounds with

(a[0].first..a[0].last))

The above is a range that will product 0..1000 which you can plug into active record, (using the hash syntax of course)

example:

Post.where(price: a[0].first..a[0].last)

make it into a resusable scope to be able to chain them to accomate the Ands or just write the raw sql.

Hope this helps

TheIrishGuy
  • 2,531
  • 19
  • 23
0

For Dynamic array length, Try this

arr = [["0", "100"], ["100", "200"]]
query_string = ""
arr.each {|a| query_string << (arr.last == a ? " price between #{a.first} and #{a.last}"    : "price between #{a.first} and #{a.last} or") }
Product.where(query_string)

Which finds the expected records

nishanthan
  • 460
  • 1
  • 5
  • 19