I have a model in Rails from which I want to pick a random entry.
So far I’ve done it with a named scope like this:
named_scope :random, lambda { { :order=>'RAND()', :limit => 1 } }
But now I’ve added an integer field ‘weight’ to the model representing the probability with which each row should be picked.
How can I now do a weighted random pick?
I’ve found and tried out two methods on snippets.dzone.com that extended the Array class and add a weighted random function, but both didn’t work or pick random items for me.
I’m using REE 1.8.7 and Rails 2.3.
Maybe I understand this totally wrong, but couldn’t you just use the column “weight” as a factor to the random number? (Depending on the Db, some precautions would be necessary to prevent the product from overflowing.)