0

environment: rails 4.2, ruby 2.2.0

I was trying to add function something like find_each, but order by id descending.
I want to use it like this.

Person.where('age > 30').find_each_desc.each do |person|
end

I add method to ActiveRecord::Batches, it works great.

# file config/initializers/active_record.rb 
module ActiveRecord
  module Batches
    def find_each_desc(options = {})
      # do something
    end
  end
end

But if move to anthoer module, use include to add method, it's not working.

# file util/find_in_batches_with_order.rb
module Util
  module FindInBatchesWithOrder
    def find_each_desc(options = {})
      # do something
    end
  end
end

# file config/initializers/active_record.rb 
module ActiveRecord
  module Batches
    include Util::FindInBatchesWithOrder
  end
end

# can get find_each_desc method
$ ActiveRecord::Batches.instance_methods
=> [:find_each, :find_in_batches, :find_each_desc]

ActiveRecord::Relation include ActiveRecord::Batches, so can find find_each_desc method in ActiveRecord::Relation instance methods, but not.

How should I do?

heroyct
  • 11
  • 4
  • Can't you just add `include Util::FindInBatchesWithOrder` in the ApplicationRecord class (rails 5) or ActiveRecord::Base class (rails 4) instead? That should make it available as an instance method for a model. – bo-oz Jul 25 '18 at 05:02
  • @bo-oz Thanks, Yes, add include ActiveRecord::Base is works great. I want to know why include is not work, but write in ActiveRecord:: Batches is works great. – heroyct Jul 25 '18 at 05:58
  • Because your model doesn't inherit from the Batches class I guess. – bo-oz Jul 25 '18 at 06:46

0 Answers0