Rails select random record

前端 未结 8 1768
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 03:46

I don\'t know if I\'m just looking in the wrong places here or what, but does active record have a method for retrieving a random object?

Something like?

<         


        
8条回答
  •  不思量自难忘°
    2020-12-03 03:55

    Strongly Recommend this gem for random records, which is specially designed for table with lots of data rows:

    https://github.com/haopingfan/quick_random_records

    Simple Usage:

    @user = User.random_records(1).take


    All other answers perform badly with large database, except this gem:

    1. quick_random_records only cost 4.6ms totally.

    1. the accepted answer User.order('RAND()').limit(10) cost 733.0ms.

    1. the offset approach cost 245.4ms totally.

    1. the User.all.sample(10) approach cost 573.4ms.

    Note: My table only has 120,000 users. The more records you have, the more enormous the difference of performance will be.


    UPDATE:

    Perform on table with 550,000 rows

    1. Model.where(id: Model.pluck(:id).sample(10)) cost 1384.0ms

    1. gem: quick_random_records only cost 6.4ms totally

提交回复
热议问题