Get a Random Record from an ActiveRecord Model
Let's say you have an events
table with a model name Event
. If you want to get a random event from the table, you could run
The functional part of this query is the ORDER BY random()
bit. For every row that postgres is sorting, it generates a random number (between 0.0 and 1.0 by default). Then it sorts the rows by their randomly generated number. Read more about the postgres random()
function at the documentation page.