Created
November 5, 2015 04:45
-
-
Save vinhnglx/5935ec6a48bc4c0a7e32 to your computer and use it in GitHub Desktop.
Random record in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Inspired from Sebastien Saunier | |
# models/production.rb | |
class Production < ActiveRecord::Base | |
enum status: {active: 1, deactive: 0} | |
validates_presence_of :status | |
include Randomable | |
end | |
# app/models/concerns/randomable.rb | |
module Randomable | |
extend ActiveSupport::Concern | |
class_methods do | |
def random(the_count = 1) | |
records = offset(rand(count - the_count)).limit(the_count) | |
the_count == 1 ? records.first : records | |
end | |
end | |
end | |
# rails console | |
2.2.0 :001 > Production.random | |
(0.5ms) SELECT COUNT(*) FROM "productions" | |
Production Load (0.2ms) SELECT "productions".* FROM "productions" ORDER BY "productions"."id" ASC LIMIT 1 OFFSET 1 | |
=> #<Production id: 2, title: "abc", price: 23, description: nil, status: 1, created_at: "2015-11-04 05:58:43", updated_at: "2015-11-04 05:58:43"> | |
2.2.0 :002 > Production.random(2) | |
(0.2ms) SELECT COUNT(*) FROM "productions" | |
Production Load (0.4ms) SELECT "productions".* FROM "productions" LIMIT 2 OFFSET 1 | |
=> #<ActiveRecord::Relation [#<Production id: 2, title: "abc", price: 23, description: nil, status: 1, created_at: "2015-11-04 05:58:43", updated_at: "2015-11-04 05:58:43">, #<Production id: 3, title: "def", price: nil, description: nil, status: 0, created_at: "2015-11-04 06:01:16", updated_at: "2015-11-04 06:01:16">]> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment