Search code examples
ruby-on-railsrails-activerecordrails-consoleruby-on-rails-8

How to automatically load model schema on rails console start?


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)

Solution

  • 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