开发者

RoR: Super and Sub classing controllers

So.. i have a method in a super controller that is the same as one in the sub controller.. all except for the redirect_to if the item doesn't save..

subclass method:

def create
some logic
respond_to do |format|
      if @template_object.save
        format.html { redirect_to({:controller=>:template_objects,:action=>:build,:id=>@template_object}) }
..
end

super method:

def create
some logic
respond_to do |format|
      if @template_object.save
        format.html { redirect_to({:controller=>:objects,:action=>:build,:id=>@object}) }
..
end

what is the best wa开发者_StackOverflow中文版y to go about this?


Do you have redirect_to in both super and sub class? In that case you might need to use a flag, like a session variable, to decide whether to use or skip redirect_to in the super class.

Devise uses a similar technique, for example, when we need to redirect_to a specific page after signing in using devise.

your super class

def method
   ...some logic...
   if !session[:redirect_var].nil?
      session.delete :redirect_var
      redirect_to ....
   end 
end

your sub class

def method
   session[:redirect_var] = 'skip_redirect' # or whatever, just create a session variable to use as a flag
   super
   ...some method...
   redirect_to ....
end


The usual "object-oriented" approach to this is to create a method that both can call, then define it differently in each of them:

def redirect_to_completed_template(template_object)
  redirect_to(...)
end

The idea is to allow sub-classes to re-define only the portion of the functionality they require. This is why you will often see specific features broken out as functions even when what they do isn't especially complicated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜