Y
Y
Yourmind2020-07-25 15:57:15
ruby
Yourmind, 2020-07-25 15:57:15

How to override the ActiveRecord::Base class method?

Good day. The problem is this:
I have many models that inherit from the Base class
For example:
class EventType < Base
... the
end

of the Base class looks like this:

class Base < ActiveRecord::Base
self.abstract_class = true
...
end

I have gem will_paginate connected and therefore, starting from the ActiveRecord::Base class, I have the paginate method

Question:
I need to slightly change the paginate method, under certain conditions I need a slightly different behavior from it for the Base class and, accordingly, all its child classes.

trying to write like this resulted in an error when starting the application. You tried to define a scope named "paginate" on the model "ActiveRecord::Base", but Active Record already defined a class method with the same name. (ArgumentError)

class Base < ActiveRecord::Base
self.abstract_class = true
include ValidateLimits::Extension

ActiveRecord::Base.class_eval do
scope :paginate, lambda { |params = {}|
puts 'Hello!'
}
end
end

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yourmind, 2020-07-27
@Yourmind

Decided in the end like this
config/initializers/will_paginate.rb

require 'will_paginate/active_record'
WillPaginate::ActiveRecord::Pagination.module_eval do
  alias_method :old_paginate, :paginate
  def paginate(options)
    #mycode
  end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question