Does anyone know how I could displa开发者_如何学编程y a list of 4 random users in RoR.
I know there is the rand() method, but I would have to apply this to an array somehow.
If the table does not contain too many entries the following will return four randomly chosen users:
User.find(:all, :order => 'RANDOM()', :limit => 4)
However, this doesn't scale since it randomizes the entire table. For tables with lots of columns this can be very IO intensive.
Another method is to only randomize the id
and then select only those rows. Something along the lines of:
# Return an array of ids randomly drawn from User
ids = ActiveRecord::Base.connection.select_values(
User.send(:construct_finder_sql, { :select => 'id',
:order => 'RANDOM()',
:limit => 4
}))
# Return the users drawn from above
users = User.find(:all, :conditions => "id IN (#{ids.join(',')})")
If you go with this, I would encapsulate it as a class method of User
.
精彩评论