Random Record is an add on for ActiveRecord to give Rails 3 Models the abilities to access random records
Random Record is released as a Ruby Gem. The gem is to be installed within a Ruby on Rails 3 application. To install, simply add the following to your Gemfile:
# Gemfile gem 'random_record'
After updating your bundle, you can use Random function within any ActiveRecord inherited model
For example you can do something like this in your controller (app/controllers/users_controller.rb), view or presenter
class UsersController < ApplicationController RANDOM_LIMIT = 5 def index @users = User.random(RANDOM_LIMIT) end def show @user = User.random end end
Random Record is implemented as a Class Method within ActiveRecord Models and can only be attached to the end of a scope chain as it uses eager loading
What does the mean, oh not so wise one?
Rails 3 uses ActiveRecord::Relation for chaining things like scopes, joins, where, or order on your model. This allows Rails to chain these scopes without returning the data until really needed. This is referred to as lazily loading.
This creates a contraint on the implementation of
random() method requires eager loading (required data has to be fetched from the database before creating a random set).
This allows us the append this random method to the end of any Arel chain.
class User < ActiveRecord::Base scope :students, where("role = ?", "Student") end class UsersController < ApplicationController RANDOM_LIMIT = 5 def index @users = User.students.order("created_at DESC").random(RANDOM_LIMIT) end def show @user = User.where("role <> ?", "Student").random end end
But it restricts us to do something like this (use this method within a scope chain)
@user = User.random(2).where("role <> ?", "Student")