ApplicationRecord vs ActiveRecord::Base
Recently,. there was a discussion amongst my colleagues about why some of the models in our Rails 8 app inherit from ApplicationRecord while others inherit from ActiveRecord::Base. Lets dig in to these subtle but important distinctions, shall we?
ApplicationRecord is a class that inherits from ActiveRecord::Base
and serves as the base class for your application’s models. It was introduced in Rails 5.0 as part of the application structure. When you generate a new Rails app, you’ll find this class defined in app/models/application_record.rb
:
rubyclass ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
ActiveRecord::Base is the fundamental base class provided by the ActiveRecord ORM that contains all the core functionality for database interactions, validations, callbacks, associations, etc.
ApplicationRecord provides a centralized place for application-wide model configuration. You can add methods, validations, callbacks, or other functionality that should be available to all your models by putting them in ApplicationRecord, rather than repeating code across individual models or monkey-patching ActiveRecord::Base. Application-specific model logic stays separate from the framework code. If you need to customize behavior for all your Rails models, modify ApplicationRecord rather than directly extending ActiveRecord::Base. Rails can make changes to ActiveRecord::Base without affecting your application-level customizations, since they’re isolated in ApplicationRecord.
If you have models inheriting directly from ActiveRecord::Base
, they’ll work fine, but the latest Rails convention going forward is to inherit from ApplicationRecord
. You can safely change existing models from ActiveRecord::Base
to ApplicationRecord
– it won’t break anything since ApplicationRecord is just a thin wrapper around ActiveRecord::Base.
So it turns out that the mixed inheritance in our app happened because some models were created before Rails 5.0 (or using older generators) while the rest were created after our previous Rail 5 upgrade. Mystery solved!