ActiveRecord: Get Me a Random Record

Sometimes you would like to test out a new feature - or perhaps isolate documented undesirable behavior - by just grabbing a random record damnit. Let’s extend the extended just for that purpose. See the Rails Model Validation - Extending ActiveRecord post for how we came with this ActiveRecord Extension. First things first. Lets address randomness. Since we use Postgres, the Postgres RANDOM function fits the bill. After the random distribution of rows, we will take the first one


#{YourRubyModel}.order("RANDOM()").first

The #{YourRubyModel} is a nice fit for class methods in our ActiveRecord extension


  # add your static(class) methods here
  module ClassMethods
    def random
      order("RANDOM()").first
    end
  end

The whole class now looks like:


cmodule ActiveRecordExtension
   extend ActiveSupport::Concern
 
   # add your instance methods here
   def issues
     unless self.valid?
       message_text = "\n ========= validation errors: =========\n"
       msg = {}
       self.errors.messages.each do |key, value|
         msg[key.to_sym] = value.first.to_s
       end
       message_text += JSON.pretty_generate(JSON.parse(msg.sort.to_h.to_json))
       message_text += "\n ========= attributes: =========\n"
       message_text += "#{JSON.pretty_generate(JSON.parse(self.attributes.sort.to_h.to_json))}\n"
       puts message_text
       "=========== for display only ============="
     end
   end
 
   def _issues
     unless self.valid?
       message_text = "\n ========= validation errors: =========\n"
       msg = {}
       self.errors.messages.each do |key, value|
         msg[key.to_sym] = value.first.to_s
       end
       message_text += JSON.pretty_generate(JSON.parse(msg.sort.to_h.to_json))
       message_text += "\n ========= attributes: =========\n"
       message_text += "#{JSON.pretty_generate(JSON.parse(self.attributes.sort.to_h.to_json))}\n"
     end
   end
 
  # add your static(class) methods here
  module ClassMethods
    def random
      order("RANDOM()").first
    end
  end
 
 end
 
 # include the extension
 ActiveRecord::Base.send(:include, ActiveRecordExtension)

Finally, fire up a console and try it out:


 :001 > Address.random

#<Address id: 10, street: "908 Denesik Flats", city: "Yesenialand", state: "KS", country: "US", zip: "67871", phone: "1-913-323-2145", fax: "1-913-305-6405", created_at: "2017-01-06 19:01:07", updated_at: "2017-01-06 19:01:07", addressable_type: "Company", addressable_id: 10, latitude: nil, longitude: nil>