为什么在around_filter或after_filter中的redirect_to不起作用?

时间:2011-05-30 23:52:40

标签: ruby-on-rails redirect filter

如何让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

3 个答案:

答案 0 :(得分:6)

操作完成后,它会自动呈现模板,因此您无法在请求完成后呈现/重定向。您可以通过将redirect_to放在所需操作的末尾来解决此问题。这不是around_filters设计的目的。

答案 1 :(得分:0)

据推测,您的操作已经有redirect_torender来电。您不能每次请求调用这些方法两次。

答案 2 :(得分:-1)

您可以更改response.location,其效果与调用redirect_to相同。一个after_filter的例子(周围可以做同样的事情):

  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