Random selection for different databases in RoR

I need to select random entries from db. In Sqlite3, which I use for development, there is a Random () function. However, in Postgresql it is called Rand (). I do not remember MySql, but it was probably called that.

So, if I have some code (for Sqlite3)

data = Items.where(pubshied: is_pubshied).order("RANDOM()").limit(count) 

How can I guarantee that it will work with different databases?

+4
source share
3 answers

Rails does not support this out of the box. I believe I achieved this with a model extension (I no longer use it because I force Postgresql), but something like this might work:

 module Randomize extend ActiveSupport::Concern included do scope :random, -> { order(rand_cmd) } end module ClassMethods def rand_cmd if connection.adapter_name =~ /mysql/i 'rand()' else 'random()' end end end end 

Then you can do

 class Item include Randomize end Item.where(...).random.limit(...) 
+4
source

For a performer, a non-adapter way of randomly arranging, filling out a random column, put an index on it and name it something like:

 Foo.order("random_column > #{rand}").limit(1) 
0
source

From the comments from the post waldyr.ar mentions in his comment: fooobar.com/questions/46558 / ....

Tl; dr: you can use Items.all.sample(count) . Of course, it retrieves the entire table and may not be useful for large tables.

-1
source

All Articles