0

I have a configuration in .irbrc that would auto connect to the database when loading rails console:

# ~/.irbrc

if defined? Rails
  # connect to db to avoid seeing `User (call 'User.connection' to establish a connection)`
  ActiveSupport.on_load(:active_record) do
    connection
  end
end

In rails 8 this doesn't work anymore:

>> ActiveRecord::Base.connection
=> #<ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x00000000007810 ...>

# Rails 7
>> User
=> User(id: integer, email: string, created_at: datetime, updated_at: datetime)

# Rails 8
>> User
=> User (call 'User.load_schema' to load schema informations)

I've tried calling ActiveRecord::Base.load_schema, but table name is required:

>> ActiveRecord::Base.load_schema
(stackoverflow):1:in '<main>': ActiveRecord::Base has no table configured. Set one with ActiveRecord::Base.table_name= (ActiveRecord::TableNotSpecified)
0

1 Answer 1

2

What you are seeing it the result of the implementation of ActiveRecord::Core#inspect.

For ActiveRecord Models, this method checks to see if the schema is loaded or that there is a connected connection (relevant if branch is)

elsif !schema_loaded? && !connected?
  "#{super} (call '#{super}.load_schema' to load schema informations)"

Your issue is that connection no longer actually establishes a connection, instead it simply returns an available connection from the pool, so initially connected? is false.

Rails 8 has actually soft deprecated ActiveRecord::ConnectionHandling::connection in favor of ActiveRecord::ConnectionHandling::lease_connection

lease_connection will return a connection (represented as an Adapter) from the ConnectionPool (if available) but that does not guarantee the connection is connected.

In order to ensure that the connection is connected you can use ActiveRecord::ConnectionAdapters::AbstractAdapter#connect!

So your code can be changed to

if defined? Rails
  # connect to db to avoid seeing `User (call 'User.connection' to establish a connection)`
  ActiveSupport.on_load(:active_record) do
    lease_connection.connect!
  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, this does it. i did connection.connect! instead so it would still work in older versions.
@Alex totally make sense. Maybe go with respond_to?(:lease_connection) ? lease_connection.connect! : connection.connect! this affords backwards compatibility and future connectivity, until the rails team changes it again. Also avoids the depreciation warning for newer versions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.