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

前端 未结 20 1401
借酒劲吻你
借酒劲吻你 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条回答
  •  温柔的废话
    2020-11-29 18:50

    Based on @TheDeadSerious's answer:

    module ActiveRecord::ConnectionSwitch  
      def on_connection(connection_spec_name)
        raise ArgumentError, "No connection specification name specified. It should be a valid spec from database.yml" unless connection_spec_name
        ActiveRecord::Base.establish_connection(connection_spec_name)
        yield
      ensure
        ActiveRecord::Base.establish_connection(Rails.env)
      end
    end
    
    ActiveRecord.send :extend, ActiveRecord::ConnectionSwitch
    

    Usage:

    ActiveRecord.on_connection "sdmstore_#{Rails.env}" do
      Widget.delete_all
    end
    

提交回复
热议问题