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
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)
精彩评论