Module: RandomRails::Adapters::ActiveRecord::Base

Defined in:
lib/random-rails/adapters/active_record/base.rb

Instance Method Summary collapse

Instance Method Details

#random(count: 1, strategy: :auto, precision: 1.0) ⇒ ActiveRecord::Base, ...

Main method to get random records efficiently

Parameters:

  • count (Integer) (defaults to: 1)

    Number of random records to return (default: 1)

  • strategy (Symbol) (defaults to: :auto)

    Sampling strategy (:auto, :tablesample, :offset, :order_by)

  • precision (Float) (defaults to: 1.0)

    For TABLESAMPLE, percentage of table to sample (default: 1.0)

Returns:



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/random-rails/adapters/active_record/base.rb', line 11

def random(count: 1, strategy: :auto, precision: 1.0)
  strategy = determine_strategy(strategy)

  relation = case strategy
  when :tablesample
    tablesample_random(precision: precision, count: count)
  when :offset
    offset_random(count: count)
  when :order_by
    order_by_random(count: count)
  else
    # Fallback to offset method
    offset_random(count: count)
  end

  # Return single object for count=1, relation for count>1
  (count == 1) ? relation.take : relation
end