Link.random(2)
and then get back random Link objects. I messed around with a couple of things, and ended up doing the following in my Link model
class Link < ActiveRecord::Base
def self.random(number)
links = Array.new
seen = Hash.new(0)
randid = 1
count = 0
number.downto(1) { |n|
loop do
randid = rand(Link.count)+1
begin
self.find(randid)
rescue
seen[randid] += 1
end
break unless seen.has_key?(randid)
end
seen[randid] += 1
puts seen.to_s
links << Link.find(randid)
}
return links
end
end
The only problem I have with the above is that it is painfully unefficient if a) the Link table is quite large, and b) if I have deleted some of the links facilitating a non-continious stretch of IDs. I will modify it sometime soon; creating an array of the existing IDs from the Link table and randomizing the index of that array should work equally well.