Extend ActiveRecord::Base
In this post, lets see how to extend ActiveRecord::Base
class to add custom methods.
In the above example module ActiveRecordExtension
has defined a module ClassMethods
which is the standard way of creating class methods to be included in other classes or modules using ActiveSupport::Concern
.
This ClassMethods
has defined a method to list top ten results.
In the end the created module ActiveRecordExtension
is included in ActiveRecord::Base
dynamically.
Create a rails initializer active_record_extension.rb and add the above code in that file.
The extension is added to the ActiveRecord::Base
on boot of the rails and ready to be used on all active record models.
Now we can use this method top_ten
on all the models.
will list last 10 employees or users created.
Similarly we can add instance methods too.
Note:
The above applies only to Rails 4.2 and below
.
With Rails 5
, ApplicationRecord
will be a single point of entry for all the customizations and extensions needed for an application, instead of monkey patching ActiveRecord::Base