I'm trying to add some custom methods to ActiveRecord. I want to add a *_after
and *_before
scopes for every date
field of a model so I can do something like this:
User.created_at_after(DateTime.now - 3.days).created_at_before(DateTime.now)
I've followed the solution explained here Rails extending ActiveRecord::Base but when I execute the rails console and try to call the methods I get an undefined method
error.
Here's my code:
# config/initializers/active_record_date_extension.rb
require "active_record_date_extension"
# lib/active_record_date_extension.rb
module ActiveRecordDateExtension
extend ActiveSupport::Concern
included do |base|
base.columns_hash.each do |column_name,column|
if ["datetime","date"].include? column.type
base.define_method("#{column_name}_after") do |date|
where("#{column_name} > ?", date)
end
base.define_method("#{column_name}_before") do |date|
where("#{column_name} < ?", date)
end
end
end
end
end
Rails.application.eager_load!
ActiveRecord::Base.descendants.each do |model|
model.send(:include, ActiveRecordDateExtension)
end
What am I doing wrong?