Adds Random Record functionality to ActiveRecord
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.
lib Updated homepage Apr 4, 2012
.gitignore git ignored .rvmrc May 25, 2011
.ruby-gemset Updated readme Jun 3, 2013
.ruby-version Updated readme Jun 3, 2013
Gemfile Added rake to development environment Sep 15, 2011
README.mdown Updated readme Jun 3, 2013
Rakefile Initial Commit May 25, 2011
random_record.gemspec Updated homepage Apr 4, 2012


Getting Started Code Climate Dependency Status Gem Version

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

  def index
    @users = User.random(RANDOM_LIMIT)

  def show
    @user = User.random

Advanced Usage

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

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")

class UsersController < ApplicationController

  def index
    @users = User.students.order("created_at DESC").random(RANDOM_LIMIT)

  def show
    @user = User.where("role <> ?", "Student").random

But it restricts us to do something like this (use this method within a scope chain)

```ruby @user = User.random(2).where("role <> ?", "Student") ```