Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Association proxy does not forward missing methods to the actual instance

#5966

Given a simple association:

class City < ActiveRecord::Base
  belongs_to :country
end

class Country < ActiveRecord::Base
  def method_missing(method, *args)
    p "method #{method} not found on #{self}"
  end
end

I am able to create objects of type Country and missing methods are correctly forwarded to my method_missing:

country = Country.new
country.non_existing_method
# prints "method non_existing_method not found on #<Country..>"

However when I create an City object and assign the country object, it stops working:

city = City.new(:country => country)
city.country.non_existing_method
# raises NoMethodError

I can work around this by using try:

city.country.try(:non_existing_method)

But that is ugly. And not intuitive.

Reported by wereHamster · November 13th, 2010 @ 01:00 PM

State: stale
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. wereHamster
    wereHamster

    Just when I posted the ticket I figured out how the association proxies work. How does this patch look?

    November 13th, 2010 @ 01:20 PM

  2. wereHamster
  3. Neeraj Singh
    Neeraj Singh
    • Importance changed from to Low

    Patch looks good. I think you should attach a test too.

    November 13th, 2010 @ 05:50 PM

  4. Cesario
    Cesario
    • Tag set to active record, 3.0

    Hi,

    Your commit makes the tests go read.

    The problem with defining method with method_missing is that @target.respond_to?(method) (in the association proxy piece of code you mention) will always returns false.

    November 13th, 2010 @ 08:21 PM

  5. rails
    rails
    • State changed from new to open
    • Tag changed from active record, 3.0 to active record, 30

    This issue has been automatically marked as stale because it has not been commented on for at least three months.

    The resources of the Rails core team are limited, and so we are asking for your help. If you can still reproduce this error on the 3-0-stable branch or on master, please reply with all of the information you have about it and add "[state:open]" to your comment. This will reopen the ticket for review. Likewise, if you feel that this is a very important feature for Rails to include, please reply with your explanation so we can consider it.

    Thank you for all your contributions, and we hope you will understand this step to focus our efforts where they are most helpful.

    February 14th, 2011 @ 12:00 AM

  6. rails
    rails
    • State changed from open to stale

    February 14th, 2011 @ 12:00 AM

  7. af001
    af001

    私の中で、総合評価のとっても低いアバアバクロホリスタークロ銀座店。アバクロは大好きなんですけどね。一昨日の東京駅付近での打ち合わせの後、散歩がてら久々に行ってきました。そしたらビックリ!相変わらアバクロず、踊っているだけの店員さんとかもいましたが、

    May 5th, 2011 @ 02:55 AM