Created
January 13, 2011 14:14
-
-
Save guimello/777911 to your computer and use it in GitHub Desktop.
Active Record random scope (Rails 2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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