Reputation: 83
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
Upvotes: 3
Views: 64
Reputation: 102222
You can use where
with a range to generate a BETWEEN statement.
Photo.where(score: ((@photo1.score-200)..(@photo1.score+200)))
.order("RANDOM()").take
Upvotes: 3