2012-01-27 60 views
1

我有一个小问题,有栏杆里面调用的时候,我希望能够做这样的事情,以避免多重重定向:如何避免多个redirect_to的方法

def render_not_found 
    not_found 
end 

private 

    def not_found 
    redirect_to website_url(@website), :status => 301 and return return 
    end 

return return不起作用当然!

使用:导轨3.2.0

+1

你为什么重定向到'website_url'之前,如果没有找到的东西?没有发现导致重定向发生的原因?请稍微解释一下你的逻辑,也许我们可以更好地帮助你。 – iwasrobbed 2012-01-27 22:38:13

+0

在我的应用程序中随处调用not_found。 website_url(@website)只是主页。 – Hartator 2012-01-28 01:00:08

回答

3

有几种方法可以做到这一点。一种方法是定义并引发自定义错误,并在发生时重定向处理程序。

application_controller.rb

Class ApplicationController < ActionController::Base 

    around_filter :catch_errors 

    def catch_errors 
    yield 
    rescue SiteNotFoundError 
    redirect_to website_url(@website), :status => 301 
    rescue ActiveRecord::RecordNotFound 
    render 404 
    rescue ... 
    ... 
    ... 
    end 
end 

class SiteNotFoundError < StandardError; end 
在控制器

def your_action 
    raise SiteNotFoundError if (some condition) 
end 

或在

过滤

before_filter :ensure_valid_site 

def ensure_valid_site 
    raise SiteNotFoundError if .... 
end 
0

我通常把我的重定向在before_filters错误。

但是,如果你真的想这样做,你可以这样做......但我警告你 它不漂亮。

def render_not_found 
    not_found(binding) 
end 

private 

def not_found(b) 
    redirect_to website_url(@website), :status => 301 
    b.eval('return') 
end