如何检查Rails迁移中的数据库类型? [英] How do I check the Database type in a Rails Migration?
问题描述
我进行了以下迁移,我希望能够检查与该环境相关的当前数据库是否是mysql数据库.如果是mysql,则我要执行特定于数据库的SQL.
I have the following migration and I want to be able to check if the current database related to the environment is a mysql database. If it's mysql then I want to execute the SQL that is specific to the database.
我该怎么办?
class AddUsersFb < ActiveRecord::Migration
def self.up
add_column :users, :fb_user_id, :integer
add_column :users, :email_hash, :string
#if mysql
#execute("alter table users modify fb_user_id bigint")
end
def self.down
remove_column :users, :fb_user_id
remove_column :users, :email_hash
end
end
推荐答案
ActiveRecord::Base.connection
将为您提供有关boot.rb
和environment.rb
ActiveRecord::Base.connection
返回很多信息.因此,您必须确切了解要查找的内容.
ActiveRecord::Base.connection
returns a lot of information. So you've got to know exactly what you're looking for.
马塞尔指出:
ActiveRecord::Base.connection.instance_of?
ActiveRecord::ConnectionAdapters::MysqlAdapter
可能是确定数据库是否为MySQL的最佳方法.
is probably the best method of determining if your database MySQL.
尽管依赖在ActiveRecord
版本之间可能会发生变化的内部信息,但我更喜欢这样做:
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"
这篇关于如何检查Rails迁移中的数据库类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!