rails, activerecord, get current connection specification

后端 未结 3 1606
刺人心
刺人心 2020-12-30 20:04

I am writing code that will migrate some data from one database to another, over-writing some data in the destination. It uses ActiveRecord, since it\'s associated with a Ra

相关标签:
3条回答
  • 2020-12-30 20:17

    Similar to the way that you can call connection on a model, you can make a call to connection on ActiveRecord::Base.

    ActiveRecord::Base.connection_config
    

    Look at the docs for ActiveRecord::Base, as there are other methods that allow you to get/set attributes about the connection.

    0 讨论(0)
  • 2020-12-30 20:25

    Rails internally instantiate a new connection depending on the DBMS being used by delegating the logic to the different supported adapters. That information is in the @connection_adapters instance variable set in the constructor:

    ActiveRecord::Base.connection.instance_variable_get(:@connection_parameters)
    

    The difference is ActiveRecord::Base.connection_config returns a hash containing the data already "mapped" for Rails purposes, you could easily instantiate a new connection by doing

    PG.connect(ActiveRecord::Base.connection.instance_variable_get(:@connection_parameters))
    
    0 讨论(0)
  • 2020-12-30 20:29

    The answer is SomeModel.connection_config

    0 讨论(0)
提交回复
热议问题