As KandadaBoggu points out above, retrieving all of the User
records from the database is inefficient when you only need 20. I would suggest using MySQL's RAND()
function to perform the randomization before you return from the database. You can still pass a seed value to RAND()
to make sure the shuffling only happens once per session.
For example:
class User < ActiveRecord::Base
def self.randomized(seed = nil)
seed = seed.to_i rescue 0
order("RAND(#{seed})")
end
end
class UsersController < ApplicationController
before_filter :set_random_seed
def index
@users = User.randomized(session[:seed]).page(params[:page]).per(20)
end
private
def set_random_seed
session[:seed] ||= Random.new_seed
end
end
I don't have a MySQL installation to test against, but this should perform better than your original code.