ruby on rails - Why does monkey patching methods on ActiveRecord::Base redefine unrelated methods on Model.count -


when monkey patch activerecord::base class methods, methods inherited different model activerecord_relation classes (like user::activerecord_relation) , can called on instances of specific active record relations. causes unexpected behavior when making active record calls original model.

here's trivial example:

user.count => 3544  users = user.where("created_at > ?", 1.month.ago) users.count => 174  class activerecord::base     def self.monkey_foo(options = {}, &block)         user.count     end end  user.monkey_foo => 3544  book.monkey_foo # model => 3544  users.monkey_foo => 173 # count of users relation, not user model  book.where("created_at > 1.year.ago").monkey_foo => 3544 # issue affects user model relations 

what causing behavior?

i know monkey patching pretty bad idea serious. accidentally discovered behavior , i'm curious know why it's happening.

the key question in delegation.rb

basically has follow method missing implementation relation (simplified brevity)

def method_missing(method,*args,&block)   scoping { @klass.public_send(method, *args, &block) } end 

(@klass active record class relation belongs to)

the scoping method sets class' current_scope duration of block. contains things clauses, sorts etc. allows call class methods on relations , have class methods operate on scope defined relation.

in book case still happening, scoping happening book query against user scoping doesn't change result.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -