我在使用 rails 时遇到了一点问题,我希望能够做这样的事情来避免多次重定向:
def render_not_found
not_found
end
private
def not_found
redirect_to website_url(@website), :status => 301 and return return
end
return return
当然不行!
使用:rails 3.2.0
最佳答案
有几种方法可以做到这一点。一种方法是定义和引发自定义错误,并有一个在发生这种情况时重定向的处理程序。
应用程序 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
在你的 Controller 中
def your_action
raise SiteNotFoundError if (some condition)
end
或在前置过滤器中
before_filter :ensure_valid_site
def ensure_valid_site
raise SiteNotFoundError if ....
end
关于ruby-on-rails - 在方法内部调用时如何避免多个 redirect_to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9040017/