:order_by => ["RAND()"]

Hi there,

I'm trying to grab a random row out of a database and I keep getting the error:

Couldn't find Reason with ID=random

Here's my controller:

@reason = Reason.find(:first, :order => ["RAND()"])

I think that's right, right? I know that RAND() is an expensive operation, but it's a small table so I'm not too worried.

Thanks!

Reason.find(Reason.find(:all, :select => :id).map(&:id).rand)

Enjoy.

or…

@reason = Reason.find(:all, :order => “RAND()”, :limit => 1)

(you might need to do a .first on the result set)

Jodi

Hmm... I tried what you have to a T (including the .first) and no luck. Weird! I'll keep trying stuff.

Jodi Showers wrote:

Hey Dave -

Hmm... I tried what you have to a T (including the .first) and no luck. Weird! I'll keep trying stuff.

Jodi Showers wrote:

the error:

Couldn't find Reason with ID=random

Here's my controller:

@reason = Reason.find(:first, :order => ["RAND()"])

I think that's right, right? I know that RAND() is an expensive operation, but it's a small table so I'm not too worried.

or..

@reason = Reason.find(:all, :order => "RAND()", :limit => 1)

(you might need to do a .first on the result set) Jodi

I'm doing that with rails 1.2.3 and mysql 5 (with a few :conditions and :includes thrown in as well).

Jodi

Thanks for the patience. I figured it out, and it was an unrelated routing error. Grr. :slight_smile:

Jodi Showers wrote:

You could also try using the find_random plugin: http://www.railslodge.com/plugins/964-find-random

I have not tried using it yet, but it looks well-executed. Has anyone tried using the find_random plugin with has_finder?

Jason Arora