Search code examples
ruby-on-railspg

Is there an easy way to get an instance of PGconn from ActiveRecord?


I have some code which relies on PGConn to connect to my database. However, I have an ActiveRecord connection already established.

Therefore, is there anyway I can get a PGConn from AR that I can use for the code in question?


Solution

  • I think you're looking for the #raw_connection method of ActiveRecord::Base.connection:

    pgconn = ActiveRecord::Base.connection.raw_connection
    

    You can also fetch the connection particular to a model class from that class's connection:

    pgconn = MyModelClass.connection.raw_connection
    

    There's a pretty good blog post by Daniel Azuma on the low-level connection API.

    Hope this helps!