代码之家  ›  专栏  ›  技术社区  ›  Shaun Mundi

如何在rails迁移中检查数据库类型?

  •  42
  • Shaun Mundi  · 技术社区  · 15 年前

    我进行了以下迁移,我想能够检查与环境相关的当前数据库是否是mysql数据库。如果是mysql,那么我想执行特定于数据库的sql。

    我该怎么办?

    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
    
    5 回复  |  直到 10 年前
        1
  •  39
  •   Vadim K.    10 年前

    ActiveRecord::Base.connection 将为您提供有关 boot.rb environment.rb

    activerecord::base.connection连接 返回大量信息。所以你必须知道你到底在找什么。

    正如马塞尔指出的:

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

    可能是确定数据库mysql是否正确的最佳方法。

    尽管依赖内部信息 ActiveRecord 释放,我更喜欢这样做:

    ActiveRecord::Base.connection.instance_values["config"][:adapter] == "mysql"
    
        2
  •  57
  •   stasl    15 年前

    更短的通话时间

    ActiveRecord::Base.connection.adapter_name == 'MySQL'
    
        3
  •  25
  •   Hauleth    12 年前

    有一个 adapter_name 在里面 AbstractAdapter 从铁路2开始就是这样。

    因此在迁移中更容易使用,如下所示:

    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
    
        4
  •  8
  •   ctide    14 年前

    在rails 3中(可能更早,但我目前使用的是rails3),使用activerecord::connectionadapters::mysql adapter是一个很糟糕的方法,因为它只有在使用的数据库适配器是mysql时才被初始化。即使安装了mysql gem,如果不是您的连接类型,调用也将失败:

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

    因此,我建议使用stasl的答案并使用连接的adapter_name属性。

        5
  •  -4
  •   CodeJoust    15 年前

    这可能有助于:

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