简体   繁体   中英

RoR random four users

Does anyone know how I could display 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM