Search code examples
ruby-on-railsdebuggingrubymine

Ruby on Rails: how do I find out where a method is called?


I am getting up to speed with an existing Rails project and am wondering where a particular attribute (field) in the model (ActiveRecord) is modified. In Java I would either use the Eclipse "find reference" feature on the setter, or set a breakpoint there. With the ActiveRecord, the attribute is not even listed in the class file! Of course I can do a text search and look through hundreds of results, but this defies the point of working with an IDE. Is there a better way? I'm using RubyMine.


Solution

  • tl;dr

    Kernel.caller

    Explanation

    Rails uses method_missing to implement attribute methods on ActiveRecord models. You can see that in the ActiveRecord::Base source code. The way I would approach this problem for a model class YourModel is like so:

    class YourModel < ActiveRecord::Base
      def myfield=(*args)
        Rails.logger.debug "myfield called at #{Kernel.caller.inspect}"
        super(*args)
      end
    end
    

    There are actually a few other ways that your attribute might get updated, such as update_attribute and friends. If you can't find the assignment call site you can keep overriding methods till you find that one that your code is using. Alternatively, you can alter ActiveRecord::Base in your local copy of the gem ("bundle show activerecord" gives the path to it).