I've done some reading about how to extend ActiveRecord:Base class so my models would have some special methods. What is the easy way to extend it (step by step tutorial)?
Ruby-on-rails – Rails extending ActiveRecord::Base
extendrails-activerecordruby-on-rails
Related Topic
- Ruby-on-rails – Rails :include vs. :joins
- Ruby-on-rails – Rails: How to rename a database column in a Ruby on Rails migration
- Ruby-on-rails – Random record in ActiveRecord
- Ruby-on-rails – Rails DB Migration – How To Drop a Table
- Ruby-on-rails – Float vs Decimal in ActiveRecord
- Ruby-on-rails – How to use concerns in Rails 4
Best Answer
There are several approaches :
Using ActiveSupport::Concern (Preferred)
Read the ActiveSupport::Concern documentation for more details.
Create a file called
active_record_extension.rb
in thelib
directory.Create a file in the
config/initializers
directory calledextensions.rb
and add the following line to the file:Inheritance (Preferred)
Refer to Toby's answer.
Monkey patching (Should be avoided)
Create a file in the
config/initializers
directory calledactive_record_monkey_patch.rb
.The famous quote about Regular expressions by Jamie Zawinski can be re-purposed to illustrate the problems associated with monkey-patching.
Monkey patching is easy and quick. But, the time and effort saved is always extracted back sometime in the future; with compound interest. These days I limit monkey patching to quickly prototype a solution in the rails console.