Defining method_missing on Active record in rails 4 throws SystemStackError: stack level too deep on attributes

StackOverflow https://stackoverflow.com/questions/16088392

Frage

I recently upgraded my app to rails 4.0 and ruby 2.0 I'm having problems understanding why my method_missing definitions won't work. I'm pretty sure I'm not doing anything differently than I was before.

Specifically, I'm trying to create a method that lets an ActiveRecord object respond to a call to an object it belongs_to via a polymorphic relationship.

Here are my classes:

song.rb

class Song < ActiveRecord::Base
    has_many :events, :as => :eventable
end

event.rb

class Event < ActiveRecord::Base

    belongs_to :eventable, :polymorphic => true

    def method_missing(meth, *args, &block)
       if meth.to_s ==  self.eventable_type
          self.eventable
       else
          super
       end
    end

end

I want to be able to call event.song when the eventable_type of event == 'Song' The issue is on the self.eventable_type, which triggers a stack overflow.

What am I missing here?

War es hilfreich?

Lösung

It seems as though the eventable_type method isn't yet defined when method_missing triggers (some methods in Rails get dynamically defined through method_missing the first time you call them).

I'd try a different means of getting the value you want; perhaps self.attributes["eventable_type"] will work?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top