Why redirect_to in around_filter or after_filter won't work?

后端 未结 3 615
天命终不由人
天命终不由人 2021-01-26 18:53

How to make redirect_to works in those filters?

I\'m trying to change

def start 
  ....
  redirect_to index
end

def end
  ...
  redirect_to index
end           


        
相关标签:
3条回答
  • 2021-01-26 19:31

    You can change response.location, which has the same effect as calling redirect_to. An example with an after_filter (the same could be done with around):

      after_filter :different_redirect, only:[:create]
      def different_redirect
        if self.status == 302
          response.location = other_thing_path
        end
      end
    
      def create
        @my_thing = MyThing.new(params[:my_thing])
        respond_to do |format|
          if @my_thing.save
            format.html { redirect_to(my_things_path) }
          else
            format.html { render :action => "new" }
          end
        end
      end
    
    0 讨论(0)
  • 2021-01-26 19:36

    After the action is complete it renders the template automatically, thus you cannot render / redirect after the request is complete. You could solve this by putting the redirect_to at the end of the actions that you need it for. This is not what around_filters were designed to do.

    0 讨论(0)
  • 2021-01-26 19:54

    Presumably, your actions already have a redirect_to or render call. You cannot call these methods twice per request.

    0 讨论(0)
提交回复
热议问题