Picture_10_normalbrupm

http://twitter.com/brupm

Re: Random Records in Rails

# Via: http://almosteffortless.com/2007/12/04/random-records-in-rails/

class Widget < ActiveRecord::Base
 
  # ...
 
  def self.random
    ids = connection.select_all("SELECT id FROM widgets")
    find(ids[rand(ids.length)]["id"].to_i) unless ids.blank?
  end
 
end

# and then...

class SomeController < ApplicationController
 
 
  def some_action
    @widget = Widget.random
  end
 
end
Reveal More
Added over 2 years ago
Post Code