3

I am opening rails console session and do:

2.6.3 :048 > ActiveRecord::Base.connected?
 => true 
2.6.3 :049 > ActiveRecord::Base.connection_pool.disconnect!
 => [] 
2.6.3 :050 > ActiveRecord::Base.connected?
 => false 
2.6.3 :051 > ActiveRecord::Base.establish_connection(:development)
 => #<ActiveRecord::ConnectionAdapters::ConnectionPool:0x00 ... >
2.6.3 :052 > ActiveRecord::Base.connected?
 => false
2.6.3 :053 > SomeModel.connection
 => #<ActiveRecord::ConnectionAdapters::PostgreSQLAdapter:0x00 ...>
2.6.3 :055 > ActiveRecord::Base.connected?
 => true
$ rails -v
Rails 5.2.3

my config/database.yml file has to be fine, because HTTP requests are working fine.

Why I cant establish connection in rails console this way?

I am asking because I have similar use of establish_connection in one of config/initializers/ file, that is configuring sneakers workers like here and there it is also returning me false on ActiveRecord::Base.connected?

2 Answers 2

1

To connect again you can use

ActiveRecord::Base.connect

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.
Sign up to request clarification or add additional context in comments.

1 Comment

thats right, but there should be ActiveRecord::Base.connection
1

To connect you can use ActiveRecord::Base.connection and than you can call Somemodel.first and its should work.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.