I was trying to make a Quote model that could feed my webapp with
random quotes. I posted about this at http://nunojob.wordpress.com/2008/02/08/random-in-ruby-on-rails
After creating the model i entered ./script/console and tried
This didn't work so I looked for another solution. Some of those
Quote.find(:all)[rand(Quote.count)] # Works but fetches all quotes and does 2 sql statetments
Quote.find_by_id rand(Quote.count) + 1 # Doesn't work if somebody deletes a quote and uses 2 sql statements.
Quote.find(:first, :order => "RAND()") # RAND is for mysql only. There no way to pass the correct sql to everyadapter
After this my friend António Medeiros made a way to do this, for my
:adapter => "mysql",
:host => "localhost",
:username => "utilizador",
:password => "password",
:database => "teste"
class Quote < ActiveRecord::Base
if args.first.to_s == "random"
super(:first, :order => self.random_command)
# Other ways to do RAND for diferent adapters.
The next step seemed to be suggesting a patch to rails core. However
I'm still a rails rookie and don't have that necessary knowledge to
understand all of that code. Can you tell me if this is already on
rails core? Can someone add it please. It seems rather easy.