Skip to Main Content
Rails
TWIL
Katie presents a Ruby on Rails coding tip on selecting a random record from a database model in the TWIL series.

Welcome to another edition of TWIL, where our developers share fun-sized insights into software craftsmanship. This week, join Katie as she demonstrates a whimsical yet handy Ruby on Rails trick by unveiling a method to fetch a Random Record from Models. Learn how just a few lines added to ApplicationRecord can elevate your code's versatility, letting you pull a surprise entry from your datasets with Ruby's elegant simplicity.

Method on models to get random record

This may not have terribly many practical applications, but it's a pretty fun method that, by adding it to ApplicationRecord, allows you to get a random record of a given class (or query set) throughout your application.

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  def self.random(*q)
    queryset = q.any? ? self.where(*q) : self
    offset = rand(queryset.count) 
    queryset.offset(offset).first
  end
end

As an example:

User.all # Emily, Frank, Katie, Marisa, Micah, Andrea, Sara, Scott

# User.all (8)
User.random # Emily  == User.offset(0).first
User.random # Micah  == User.offset(4).first
User.random # Marisa == User.offset(3).first

# User.where(has_dog: true) (6: Emily, Frank, Katie, Micah, Andrea, Scott)
User.random(has_dog: true) # Katie  == User.where(has_dog: true).offset(2).first
User.random(has_dog: true) # Frank  == User.where(has_dog: true).offset(1).first
User.random(has_dog: true) # Andrea == User.where(has_dog: true).offset(4).first

# User.where(mean: true) (0)
User.random(mean: true) # nil == User.where(mean: true).offset(0...).first
  • Ruby
  • Rails
Katie Linero's profile picture
Katie Linero

Senior Software Engineer

Related Posts

Demonstration of GDPR compliant data security practices using handheld device.
June 7, 2018 • Nick Farrell

Techniques for Personal Data Privacy

Over the past decade, we’ve seen what can happen when companies are neglectful with personal data, and in 2018, strong privacy practices can ensure that your company is making headlines for the right reasons.

Software development represented by an abstract pattern and a parrot illustration, displaying technical creativity.
September 13, 2018 • Katie Linero

Pronouncing Things with Amazon’s Polly

Cuttlesoft engineer, Katie Linero, built an impressive solution that reads IPA phonetic notation using AWS’ Polly and Lambda.