开发者

Better Way to Randomize (Ruby/Rails 3) [duplicate]

This question already has answers here: Rails select random record 开发者_运维百科 (8 answers) Closed 5 years ago.

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?


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

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


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) }


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜