Last Updated: February 25, 2016
·
1.125K
· gobert

Random record for all ActiveRecord model.

You are also used to query random record from ActiveRecord with something like:

random_record = User.offset(rand(User.count)).first

The following monkey patch will add a rand class method to all your ActiveRecord models:

module ActiveRecord
  module FinderMethods
    def rand
        # super = method(:rand)
        # => #<Method: Object(Kernel)#rand>
        klass = self.class.to_s.split('::').first.constantize
       self.offset(super(klass.count)).first
    end
  end
end

module ActiveRecord
  module Querying
    delegate :rand, to: :all
  end
end

Example:

 User.rand
=> #<User id: 1569>
 User.rand
=> #<User id: 1532>
 User.rand
=> #<User id: 1647>

Tested against ActiveRecord 4.0.0

1 Response
Add your response

I really like your trick. Thanks for sharing

over 1 year ago ·