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
Event.find_by_sql(
<<-SQL
SELECT * FROM events ORDER BY random() LIMIT 1
SQL
).first
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.