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

北城以北 提交于 2019-11-28 06:43:38
EmFi

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"

Even more shorter call

ActiveRecord::Base.connection.adapter_name == 'MySQL'
KARASZI István

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_sym
case adapter_type
when :mysql
  # do the MySQL part
when :sqlite
  # do the SQLite3 part
when :postgresql
  # etc.
else
  raise NotImplementedError, "Unknown adapter type '#{adapter_type}'"
end

In Rails 3, (maybe earlier, but I'm using Rails 3 currently) using ActiveRecord::ConnectionAdapters::MysqlAdapter is a poor way to go about it, as it's only initialized if the database adapter in use is MySQL. Even if you have the MySQL gem installed, if it's not your connection type, that call wil fail:

Loading development environment (Rails 3.0.3)
>> ActiveRecord::Base.connection.instance_of? ActiveRecord::ConnectionAdapters::MysqlAdapter
NameError: uninitialized constant ActiveRecord::ConnectionAdapters::MysqlAdapter
from (irb):1

So, I'd recommend stasl's answer and use the adapter_name property of the connection.

This might help:

execute 'alter table users modify fb_user_id bigint WHERE USER() = "mysqluser";'

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!