Table of contents
    blog cover

    How to Display All Model Attributes in Rails Console for Rails 7.2

    Ruby on Rails
    Ruby on Rails
    With the release of Rails 7.2, a new change was introduced to the way ActiveRecord models are inspected in the Rails console. Prior to this version, calling inspect on an ActiveRecord model instance would display all the model's attributes by default. However, in Rails 7.2, the default behavior was modified to only show the model's ID when inspect is called. This change aims to improve performance, especially in production environments where large object inspections can become a bottleneck.

    For many developers, this change was unexpected and led to confusion and inconvenience. IMO, they should show all attributes by default and let the developer specify which attributes should be hidden. But they did the opposite.

    See details in this PR: https://github.com/rails/rails/pull/49765

    The Fix: Displaying All Attributes in the Rails Console

    Fortunately, there's an easy way to revert to the previous behavior and display all attributes of a model when calling inspect. By adding a single line of configuration to your ApplicationRecord, you can ensure that all attributes are shown.
    // language: ruby
    class ApplicationRecord < ActiveRecord::Base
      primary_abstract_class
    
      # Ensure all attributes are shown when calling inspect in Rails console
      self.attributes_for_inspect = :all
    end

    If you need more granular control, you can override this setting on a per-model basis. For example, you want to display only some attributes for model User, you can set:
    // language: ruby
    class User < ApplicationRecord
      self.attributes_for_inspect = [:id, :total, :status]
    end

    Please consider your environment and performance implications when making this change, and customize it as needed for your specific use case.

    Happy coding!
    Created at 2024-09-01 22:39:00 +0700

    Related blogs