Postgresql Rails: select a random entry within a specific range?

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

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

      

I want to select another random photo as @ photo2, but its rating attribute must be +/- 400 from @ photo1 rating. How should I do it?

Optional: I prefer @ photo2 to be within +/- 200 @ photo1, and if not, search +/- 400

+3


source to share


1 answer


You can use where

with a range to create a BETWEEN statement.



Photo.where(score: ((@photo1.score-200)..(@photo1.score+200)))
     .order("RANDOM()").take

      

+3


source







All Articles