Reputation: 13927
I need to get a random record where the value of a field status
is 2
.
Upvotes: 0
Views: 48
Reputation: 4880
If you're worried about speed this might be faster:
Model.where(status: 2).offset(rand(Model.where(status: 2).count)).first
Upvotes: 2
Reputation: 211670
The really hack way to do this is:
Model.where(:status => 2).order('RAND()').first
Note that ORDER BY RAND()
can be brutally slow on large tables, but for small ones it's fine.
Upvotes: 1