ruby - Rails STI: Subclass methods not being called as expected -


i have sti implementation:

class instruction < activerecord::base   def get_view     return "i'm pseudo abstract base method!"   end end  class screatewebpage < instruction   def get_view     return "i'm doing terribly important things!"   end end 

i've added following instruction class:

def self.inherited(child)     child.instance_eval       def model_name         instruction.model_name       end     end     super   end  %w(s_create_web_page).each {|r| require_dependency r } if rails.env.development?  

=========

my database table appears storing subclass names in type column, , i've verified subclasses loaded:

(rdb) module.const_get("screatewebpage") screatewebpage(id: integer, name: string, code: string, skwerkflow_id: integer, created_at: datetime, updated_at: datetime, factory_id: integer, type: string) 

===========

the method get_view called in create method of instruction.rb. thinking each of these specific instructions can have own view. get_view little bit of metaprogramming put right view call.

problem: when call get_view on instruction has been instantiated , saved subclass, it's not calling subclass method instead calling base class:

[30, 39] in /users/alexedelstein/dev/skwerl/app/models/instruction.rb    30    end    31      32    #overridden subclass controller find right class-specific view.    33    def get_view    34      debugger => 35        return "i'm pseudo abstract base method!"    36      return nil    37    end    38      39    debugger (rdb:13) self #<instruction id: 87, name: "create web page", code: nil, skwerkflow_id: 38, created_at: "2013-07-18 01:00:40", updated_at: "2013-07-18 01:00:40", factory_id: nil, type: "screatewebpage"> 

==============

this first posting stack overflow after years of lurking, please deflower me gently. cheers.

by looking @ output looks calling method on instruction instance. screatewebpage instances instruction instances can instruction instances regardless of type column value. should double check performing screatewebpage.find(id) , not instruction.find(id).

sometimes use #becomes in abstract methods in order not worry types , not perform additional queries:

class instruction   def get_view     self.becomes(self.type.constantize).get_view   end end 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -