# 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 :
- class Random < ActiveRecord::Base
- def do_stuff
- case connection.class
- when ActiveRecord::ConnectionAdapters::MysqlAdapter
- find( :all, :order => "RAND()" )
- when ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- find( :all, :order => "RANDOM()" )
- else
- raise "Merrrrh."
- end
- end
- 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 :
- if ActiveRecord::ConnectionAdapters.constants.include? MysqlAdapter
- ...
- else ...
- ...
- end