Should establish connection when starting a console

Right now, if you have a new application with some models (such as Project), if you open the console, this will happen:

:001 > Project
=> Project (call 'Project.connection' to establish a connection)

To me, this is an extra step that I never want to not take. So I always workaround it by adding an initializer:

Rails.application.console do
  # Start the connection right away. This avoids cases like opening the console and doing this:
  # :001 > Project
  #  => Project (call 'Project.connection' to establish a connection)
  # When you clearly wanted to see the Project's attributes
  ApplicationRecord.connection
end

I personally fail to see a case where I would prefer the “don’t connect right away” option, so I’m thinking that maybe this should be the default?

Note, if any of your initializers or models or controllers or lib or … uses the database during startup, then this behavior is skipped and the connection will be already established when you reach the console. So it is pretty likely that, for most applications, the current default behavior goes away at one point just because someone wrote unrelated code. So in a way, I feel this is mostly friction for new comers only.

10 Likes

But then you can’t start the console in case the database connection doesn’t work (yet). You can’t even debug it. I think it used to be like this in the past. Maybe it should try to connect and show a warning in case the database connection fails?

1 Like