我进行了以下迁移,我希望能够检查与该环境相关的当前数据库是否是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迁移中的数据库类型?
发布评论