December 28, 2015
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
.
class Post < ApplicationRecord
end
What happened to ActiveRecord::Base
?
Well not much changed in reality. Following file will be automatically added to models in Rails 5 applications.
# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
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.
module MyAwesomeFeature
def do_something_great
puts "Doing something complex stuff!!"
end
end
ActiveRecord::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.
class ApplicationRecord < ActiveRecord::Base
include MyAwesomeFeature
self.abstract_class = true
end
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
.
# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
If this blog was helpful, check out our full blog archive.