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
Written by gobert
Related protips
1 Response
I really like your trick. Thanks for sharing
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#