RAILS RANDOM RECORDS WITH RANDUMB GEM

If you ever needed to pick some random record inside a rails app, you probably ended up writing some named scope like the following:

  class Product < ActiveRecord::Base
    scope :random, lambda { |n| scoped.limit(n).order('RAND()') }
  end

  Product.random(3)

which picks 3 random products from the database.

Of course this works fine, but it has a major drawback: the SQL random function is hardcoded in the model and if in the future you ever happen to change the database (ie you decide to host your app on Heroku, where postgres is the default RDBMS) your code will not work anymore, because it was developed according to MySQL APIs.

Here it comes randumb to rescue: just add in your gemfile gem 'randumb' and you’re done, you can query your db for random products with the same interface and the gem will apply the correct random function according to your current RDBMS. Happy coding!

Leave a Reply

Please Login to comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.