Understanding how establish_connection works in ActiveRecord

AR calls establish_connection only once, for ActiveRecord::Base. All subclasses use the one connection.

You can manually call establish connection yourself on some subclasses. This is very convenient for using two databases at once, e.g.

class MyMainUser < ActiveRecord::Base; end 
class MyOtherDb < ActiveRecord::Base; end
class MyOtherUser < MyOtherDb; end

MyOtherDb.establish_connection ...

MyMainUser.first # uses default db
MyOtherUser.first # uses other db

You can’t do queries that would cross databases though.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)