代码之家  ›  专栏  ›  技术社区  ›  Pelle

动态切换Rails数据库连接

  •  0
  • Pelle  · 技术社区  · 6 年前

    我在rails5应用程序中有一个dev数据库,但是在我们的网络中,我们还保留了一个填充的数据库来测试东西。有时,我不得不一直在这些数据库之间切换,如果我能在Rails运行时立即切换,我会节省很多时间。

    这就是我所尝试的:

    Product.count
      => 0 # is dev db
    
    ActiveRecord::Base.connection_handler.remove_connection('development')
    ActiveRecord::Base.connection_handler.remove_connection('primary')
    ActiveRecord::Base.configurations['development'] = test_config_params
    
    Product.count
    
    => 0 # Is still dev db
    

    1 回复  |  直到 6 年前
        1
  •  2
  •   R. Sierra    6 年前

    可以使用更改数据库连接 ActiveRecord::Base.establish_connection(config) . 万一 ActiveRecord::Base.configurations :development :test

    检查完整的文档 here