Victor
Victor

Reputation: 23972

Select n objects randomly with condition in Rails

I have a model called Post, with a column called vote, and it has a big number of posts

I want to select n posts randomly that have >=x votes. n is very small compared to the number of posts

What is the best way to do this? I've tried a couple of ways that seem to be very inefficient. Thanks

Upvotes: 4

Views: 212

Answers (1)

Anurag
Anurag

Reputation: 141889

If you're on MySQL, you could order all the posts that meet the greater than criteria randomly and select the top n.

The actual query would look like

SELECT * FROM posts WHERE votes >= x ORDER BY rand() LIMIT n

Haven't tested this, but something like this should work in Rails:

Post.all(:conditions => ["votes >= ?", x], :order => "rand()", :limit => n)

Upvotes: 2

Related Questions