Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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)
share|improve this question
add comment

2 Answers

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

share|improve this answer
 
can you check my question edited –  Editme Here Nov 23 at 19:18
 
Use scopes as I said. –  TheIrishGuy Nov 23 at 19:32
 
sorry am not familiar with scope can you give any sample here –  Editme Here Nov 23 at 19:41
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.