On Mon, Apr 19, 2010 at 12:47 PM, Vladimir R.
[email protected] wrote:
They’re not the same, right.
I mean, it depends on what you need. The real ID or just an amount of
But If task is to get random record you will
Company.all[rand(Company.count)] but not
I assume you meant find rather than all.
Neither of these will work in the face of deleted records, picking a
random record is a bit tricky.
One way, which might not work for all databases, but assuming a mysql
database might be:
Company.first( :order => “Rand()”)
But this isn’t very efficient and might not work for tables with lots
Another approach is something like.
Company.first(:conditions => [“id <= ?”, rand(Company.last.id) + 1]
This should always return a random record (unless the table is empty),
but the records won’t be evenly distributed because the probability of
selecting a particular record is proportional to the difference
between it’s id and the id of the preceding existing record if any, or