This blog is part of our Rails 5 series.
Rails 5 beta-1 was recently released and one of the notable change was introduction of ApplicationRecord.
Up to Rails 4.2, all models inherited from ActiveRecord::Base. But starting from Rails 5, all models will inherit from ApplicationRecord.
1class Post < ApplicationRecord 2end
What happened to ActiveRecord::Base ?
Well not much changed in reality. Following file will be automatically added to models in Rails 5 applications.
1# app/models/application_record.rb 2class ApplicationRecord < ActiveRecord::Base 3 self.abstract_class = true 4end
This behavior is similar to how controllers inherit from ApplicationController instead of inheriting from ActionController::Base.
Now ApplicationRecord will be a single point of entry for all the customizations and extensions needed for an application, instead of monkey patching ActiveRecord::Base.
Say I want to add some extra functionality to Active Record. This is what I would do in Rails 4.2.
1module MyAwesomeFeature 2 def do_something_great 3 puts "Doing something complex stuff!!" 4 end 5end 6 7ActiveRecord::Base.include(MyAwesomeFeature)
But now, ActiveRecord::Base forever includes MyAwesomeFeature and any class inheriting from it also includes MyAwesomeFeature even if they don't want it.
This is especially true if you are using plugins and engines where monkey patching to ActiveRecord::Base can leak into engine or plugin code.
But with ApplicationRecord, they will be localized to only those models which are inheriting from ApplicationRecord, effectively only to your application.
1class ApplicationRecord < ActiveRecord::Base 2 include MyAwesomeFeature 3 4 self.abstract_class = true 5end
Migrating from Rails 4
By default all new Rails 5 applications will have application_record.rb. If you are migrating from Rails 4, then simply create app/models/application_record.rb as shown below and change all models to inherit from ApplicationRecord instead of ActiveRecord::Base.
1# app/models/application_record.rb 2class ApplicationRecord < ActiveRecord::Base 3 self.abstract_class = true 4end