A ruby based approach to selecting random records(as explained in HowtoSelectRandomRecords). This approach extends ActiveRecord with a random_sample method.
/lib directory module Enumerable
def random_sample(n)
sort_by { rand }.slice(0, n)
end
end
module RandomSample
def self.append_features(base)
def base.random_sample(n = 1)
r = find(find_by_sql(“select #{primary_key} from #{table_name}”).random_sample(n).map { |q| q.id })
end
end
end
\config\environment.rb file:
class ActiveRecord::Base
include RandomSample
end
RandomSample adds a single method random_sample to all \ActiveRecord objects. random_sample will return an array of records, or nil if none were found.
irb(main):001:0> Keyword.random_sample(3)
=> [#<Keyword:0x3bde0b8 @attributes={"word"=>"tall", "id"=>"1", "genre"=>nil}>, #<Keyword:0x3bde040 @attributes={"word"=
>"dancer", "id"=>"4", "genre"=>nil}>, #<Keyword:0x3bddf68 @attributes={"word"=>"masked", "id"=>"5", "genre"=>nil}>]
irb(main):002:0> Keyword.random_sample(1).first.word
=> "tights"
irb(main):003:0> Keyword.random_sample(1).first.word
=> "superhero"
category: Example
Note: At least on my setup, this returns a random sample, but sorted (ascending ID by default)
Since I needed random order as well, I modified it slightly:
module RandomSample
def self.append_features(base)
def base.random_sample(n = 1)
r = find(find_by_sql("select #{primary_key} from #{table_name}").random_sample(n).map { |q| q.id })
# added another sort to ensure random ordering
r = r.sort_by { rand }
end
end
end
How can we modify this code to make the random a litte less random. I would like for example to be able to have a different random each weeks… so the random should care about the Time… i ve tried to replace the “rand” by somehing like Time.now etc… but nothing worked at all… any idea ?
thanks a lot