subscribe to this site

Random entries
March 24, 2008 14:21 (almost 4 years ago)
A recent challange I encoutered was getting random entries from a model. In particular, I wanted to get x number of random Links from my link database. Essentially, I wanted to by able to say

 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.









You are currently not logged in.

valid xhtml using the power of css Debian GNU/Linux served by lighttpd powered by ruby on rails