Twitterprofilephoto_normalmaranh

http://twitter.com/maranh

Re: Re: Random Records in Rails

# This code isn't database agnostic. 
 
  def self.random
    find(:first, :order => "RAND()", :limit => 1)
  end
 
# SQLite3::SQLException: no such function: RAND: SELECT * FROM "widgets"  ORDER BY RAND() LIMIT 1

# Flowcoder needs a comment system! <3
# I only work with mysql databases you could change it to RANDOM() for sqlite, but that won't help much since you probably have # a mysql / postsql production database. I'll edit my post to mention that.
Reveal More
Added 11 months ago

Funky Array Magic

a = [["Rick Ashley", "2.5"], ["Cher", "2.5"], ["Rick Ashley", "3.7"], ["Cher", "3.3"]]
a.inject({}) { |result, array| result[array[0]] ||= []; result[array[0]] << array[1];  array[1]; result }.to_a.map{ |x| x.flatten}
=> [["Rick Ashley", "2.5", "3.7"], ["Cher", "2.5", "3.3"]]
Reveal More
Added 11 months ago

Re: Random Records in Rails

class Widget < ActiveRecord::Base
 
  # ...
  # Only for mysql
  # RANDOM() will work for sqlite
  def self.random
    find(:first, :order => "RAND()", :limit => 1)
  end
 
end

# and then...

class SomeController < ApplicationController
 
  # ...
 
  def some_action
    @widget = Widget.random
  end
 
end
Reveal More
Added 11 months ago
Post Code