Miles Keaton
2005-Jul-17 08:12 UTC
Controller Inheritance again ... how to share db-accessing methods?
I''m doing this same thing : (Controller Inheritance), described here: http://justinfrench.com/index.php?id=122 But - in my inherited controller (AdminAreaController in his example) - how can I put methods that access the database stuff? (How can one common/shared controller use a different model depending on what controller has inherited it and calling it at this moment?) EXAMPLE: ====== BAD BAD BAD : =====class NewsController < ApplicationController def show @items = News.find(params[:id]) end end class DatesController < ApplicationController def show @items = Dates.find(params[:id]) end end class LinksController < ApplicationController def show @items = Links.find(params[:id]) end end HOW CAN I DO THIS? ======== ? POSSIBLE ? =====class SharedController < ApplicationController def show @item = self.mymodel.find(params[:id]) end def list @items = self.mymodel.find(:all) end end class NewsController < SharedController def self.mymodel ; News ; done end class DatesController < SharedController def self.mymodel ; Dates ; done end class LinksController < SharedController def self.mymodel ; Links ; done end It doesn''t work as-is. Maybe I''m missing something simple?
Steve Downey
2005-Jul-17 17:25 UTC
Re: Controller Inheritance again ... how to share db-accessing methods?
Miles Keaton <mileskeaton@...> writes:> > I''m doing this same thing : (Controller Inheritance), described here: > http://justinfrench.com/index.php?id=122 > > But - in my inherited controller (AdminAreaController in his example) > - how can I put methods that access the database stuff? > > (How can one common/shared controller use a different model depending > on what controller has inherited it and calling it at this moment?) >I''m sure there''s a more elegant way to get the class name from the model symbol, but here''s what I''m doing: Parent Controller: class ParentController < ApplicationController def set_class_name(class_name) @class_name = class_name end def record_class Kernel.const_get @class_name end def detail @record_detail = record_class.find(params[:id]) end end Child Controller: class ChildController < ParentController model :child_model def initialize super set_class_name "ChildModel" end end