application_record.rb available since rails 5


Bookmark and Share

Those who have been starting with Rails 5, must have noticed the new application_record.rb file present in your model folder. And all new models seems to be inheriting the application_record.rb instead of the ActiveRecord::Base. This is done so that we don’t pollute the ActiveRecord::Base namespace with our own extensions.  Before when we require something, say an extension to the ActiveRecord itself we used to have it included using the following code.

Now the problem with this approach is that when we use rails engines this NewFeature gets added in there as well, and it could end up doing things that we didn’t expect.

With the new application_record.rb, which would be inherited by all the models, we need to include the new module at the ApplicationRecord and it would be available as the new feature of ActiveRecord. Every new engine generated using rails plugin new would also be having their own application_reocord.rb

One more point to note is that we can place application wide hooks in this file. So if you were to do

it would be triggered when a new record is created in any of the models of the rails application.

Read More