How do I check the Database type in a Rails Migration? How do I check the Database type in a Rails Migration? ruby ruby

How do I check the Database type in a Rails Migration?


Even more shorter call

ActiveRecord::Base.connection.adapter_name == 'MySQL'


ActiveRecord::Base.connection will provide you with everything you ever wanted to know about the database connection established by boot.rb and environment.rb

ActiveRecord::Base.connection returns a lot of information. So you've got to know exactly what you're looking for.

As Marcel points out:

ActiveRecord::Base.connection.instance_of?   ActiveRecord::ConnectionAdapters::MysqlAdapter 

is probably the best method of determining if your database MySQL.

Despite relying on internal information that could change between ActiveRecord release, I prefer doing it this way:

ActiveRecord::Base.connection.instance_values["config"][:adapter] == "mysql"


There is an adapter_name in AbstractAdapter and that is there since Rails2.

So it's easier to use in the migration like this:

adapter_type = connection.adapter_name.downcase.to_symcase adapter_typewhen :mysql, :mysql2  # do the MySQL partwhen :sqlite  # do the SQLite3 partwhen :postgresql  # etc.else  raise NotImplementedError, "Unknown adapter type '#{adapter_type}'"end