[Skip To Content]


# DBMS-specific queries with Rails

Have you ever wanted to run queries which are specific to the type of database you’re connected to in Rails? Well, here’s one way of doing it :

  1. class Random < ActiveRecord::Base
  2. def do_stuff
  3. case connection.class
  4. when ActiveRecord::ConnectionAdapters::MysqlAdapter
  5. find( :all, :order => "RAND()" )
  6. when ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
  7. find( :all, :order => "RANDOM()" )
  8. else
  9. raise "Merrrrh."
  10. end
  11. end
  12. end

Is there a better way? Answers on a postcard …

Update : This broke in either Rails 2.0 or 2.1. Rails’ new behaviour is to only load the connection adapters you’re actually using, so you’ll need to do something like this instead :

  1. if ActiveRecord::ConnectionAdapters.constants.include? MysqlAdapter
  2. ...
  3. else ...
  4. ...
  5. end

More about this site...

Last Week’s Top 5 Albums (More »)

  1. Conor OberstConor Oberst
  2. Cruel TownBroder Daniel
  3. Far From the Maddening CrowdsChicane
  4. The Midnight Organ FightFrightened Rabbit
  5. Perfect CureLorraine