alt
alt

Reputation: 13927

Rails get random record where field has specific value

I need to get a random record where the value of a field status is 2.

Upvotes: 0

Views: 48

Answers (2)

mind.blank
mind.blank

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

tadman
tadman

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

Related Questions