Skip to content

Instantly share code, notes, and snippets.

@guimello
Created January 13, 2011 14:14
Show Gist options
  • Save guimello/777911 to your computer and use it in GitHub Desktop.
Save guimello/777911 to your computer and use it in GitHub Desktop.
Active Record random scope (Rails 2)
named_scope :random, lambda { |*args| { :joins => "JOIN (SELECT id
FROM #{table_name}
ORDER BY RAND()
LIMIT #{(limit = args.first.to_i) > 0 ? limit : 1}
) AS random_ids
ON #{table_name}.id = random_ids.id"}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment