Select n objects randomly with condition in Rails

I have a model called Post, with a column called voting, and it has a large number of posts

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

What is the best way to do this? I have tried several ways that seem very inefficient. Thanks

+4
source share
1 answer

If you use MySQL, you can sort all messages that meet random criteria that exceed the criteria, and select the top n.

The actual request will look like

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

Did not test this, but something like this should work in Rails:

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

Source: https://habr.com/ru/post/1299847/


All Articles