【问题标题】:Why redirect_to in around_filter or after_filter won't work?为什么 around_filter 或 after_filter 中的 redirect_to 不起作用?
【发布时间】:2011-05-30 23:52:40
【问题描述】:

如何让 redirect_to 在这些过滤器中工作?

我正在尝试改变

def start 
  ....
  redirect_to index
end

def end
  ...
  redirect_to index
end  

around_filter :around

def around
  ...
  yield
  redirect_to index
end 

def start
  ..
end

def stop
  ...
end

【问题讨论】:

    标签: ruby-on-rails redirect filter


    【解决方案1】:

    动作完成后它会自动渲染模板,因此在请求完成后你不能渲染/重定向。您可以通过将redirect_to 放在您需要的操作的末尾来解决此问题。这不是 around_filters 的设计初衷。

    【讨论】:

      【解决方案2】:

      大概,您的操作已经有redirect_torender 调用。您不能在每个请求中调用这些方法两次。

      【讨论】:

        【解决方案3】:

        您可以更改response.location,其效果与调用redirect_to 相同。 after_filter 的示例(同样可以使用 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
        

        【讨论】:

          猜你喜欢
          • 2017-06-14
          • 1970-01-01
          • 2013-12-19
          • 2017-07-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多