Using Rails Migration on different database than standard “production” or “development”

前端 未结 20 1434
借酒劲吻你
借酒劲吻你 2020-11-29 18:18

I have a rails project running that defines the standard production:, :development and :test DB-connections in config/database.yml

In addition I have a quiz_developm

20条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 18:59

    module ActiveRecord::ConnectionSwitch
      def on_connection(options)
        raise ArgumentError, "Got nil object instead of db config options :(" if options.nil?
        ActiveRecord::Base.establish_connection(options)
        yield
      ensure
        ActiveRecord::Base.establish_connection ActiveRecord::Base.configurations[Rails.env]
      end
    end
    
    ActiveRecord.send :extend, ActiveRecord::ConnectionSwitch
    

    If you place this inside config/initializers/ you'll be able to do something like this:

    ActiveRecord.on_connection ActiveRecord::Base.configurations['production'] do
      Widget.delete_all
    end
    

    This will delete all widgets on the production db and make sure the connection to the current Rails env's db is re-established after that.

    If you just want to make it available in your migrations insead extend the ActiveRecord::Migration class.

提交回复
热议问题