4

I'm currently using:

@users = User.order("RANDOM()").limit(6)

to generate a list of 6 random users - however, this method takes a 1200ms toll on page load times. Is there a faster/more efficient way to call 6 random users?

neon
  • 2,811
  • 6
  • 30
  • 44
  • Something like http://stackoverflow.com/questions/2279706/select-random-row-from-an-sqlite-table/4740561#4740561 ? – captainpete Jun 21 '11 at 01:05
  • 1
    have you considered this: http://stackoverflow.com/questions/3641057/rails-select-random-record/3641112#3641112 – dexter Jun 24 '11 at 07:05

5 Answers5

1

I ended up using the method described here: Rails select random record

@ramc - Thank you for your comment. Load times are now much faster :)

Community
  • 1
  • 1
neon
  • 2,811
  • 6
  • 30
  • 44
0

Assuming auto increment ids, starting from 0 and that User objects are never deleted, the following should be quite fast:

@users = (0..5).map { User.find(rand * User.count) }

Redbeard
  • 988
  • 5
  • 8
0

Have you tried using a random offset & limit?

class User < ActiveRecord::Base

  def self.random num = 1
    num.times.map { offset(rand(count)).limit(1) }
  end

end

@users = User.random(6)

I've used something similar to get single random instances from AR. You'd have to make it a bit smarter if you wanted to guarantee unique results.

BM5k
  • 1,210
  • 10
  • 28
0

You could get a random Page of users instead. Consider this pagination call using Kaminari

User.order('created_at').page(rand(User.count)).per(6)

This will fire one count query and one query for the page of 6 Users

irfn
  • 560
  • 3
  • 11
-2

You could try using array shuffle instead of using mysql random as it can be slow:

@users = User.all.shuffle[0..5]

After all, a collection of ActiveRecord objects is still just an Array

Adam Carlile
  • 416
  • 3
  • 14
  • This code is valid, but the load times are the same. :( – neon Jun 21 '11 at 21:45
  • This also loads the entire User collection - performance will get worse as the number of user records increases. – theTRON Jun 22 '11 at 09:03
  • Loading the entire collection is not something you want to do, if the database does it you will not need to fetch every rows. – Schmurfy Jun 30 '11 at 21:16