Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql Rails: Select random record within a certain range?

I have in my controller the following code to select a random photo:

@photo1 = @contest.photos.limit(1).order("RANDOM()")

I wish to select another random photo as @photo2 but its score attribute must be +/- 400 of @photo1's score. How would I do this?

Optional: I rather @photo2 be within +/- 200 of @photo1's score, and if there isn't any, then search +/- 400

like image 540
2paws Avatar asked Dec 20 '25 14:12

2paws


1 Answers

You can use where with a range to generate a BETWEEN statement.

Photo.where(score: ((@photo1.score-200)..(@photo1.score+200)))
     .order("RANDOM()").take
like image 168
max Avatar answered Dec 22 '25 08:12

max



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!