On Mon, Apr 19, 2010 at 12:47 PM, Vladimir Rybas
<[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
> records.
> But If task is to get random record you will
> Company.all[rand(Company.count)] but not
> Company.all[rand(Company.last.id)]

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
of records.

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
0.

-- 
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Github: http://github.com/rubyredrick
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to