Why belongs_to/has_many cannot overwrite methods with the same name

Updated . Posted . Visible to the public.

When you use a belongs_to or has_many macro you might be surprised that the methods that it generates does not override a method with the same name. Take this example:

class Project < ActiveRecord::Base
  
  def user
    "foo"
  end
  
  belongs_to :user
  
end

Project.new.user still returns "foo".

The reason for this is that what belongs_to does is actually this:

class Project < ActiveRecord::Base
  include FeatureMethods
  
  def user
    "foo"
  end
  
end

module Project::FeatureMethods

  def user
    # association getter goes here
  end
  
end

I'm sorry.

Henning Koch
Last edit
Felix Eschey
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2014-03-12 12:21)