Read more

Why belongs_to/has_many cannot overwrite methods with the same name

Henning Koch
March 12, 2014Software engineer at makandra GmbH

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
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2014-03-12 13:21)