What's the 'Rails 4 Way' of finding so

2019-01-21 18:58发布

User.find(:all, :order => "RANDOM()", :limit => 10) was the way I did it in Rails 3.

User.all(:order => "RANDOM()", :limit => 10) is how I thought Rails 4 would do it, but this is still giving me a Deprecation warning:

DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a relation, you can call #load (e.g. `Post.where(published: true).load`). If you want to get an array of records from a relation, you can call #to_a (e.g. `Post.where(published: true).to_a`).

9条回答
SAY GOODBYE
2楼-- · 2019-01-21 19:45

You could call .sample on the records, like: User.all.sample(10)

查看更多
够拽才男人
3楼-- · 2019-01-21 19:51

For MYSQL this worked for me:

User.order("RAND()").limit(10)
查看更多
祖国的老花朵
4楼-- · 2019-01-21 19:51

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

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

  1. quick_random_records only cost 4.6ms totally.

enter image description here

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

enter image description here

  1. the offset approach cost 245.4ms totally.

enter image description here

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

enter image description here

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

enter image description here

  1. gem: quick_random_records only cost 6.4ms totally

enter image description here

查看更多
登录 后发表回答