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