【发布时间】:2010-11-04 12:34:06
【问题描述】:
我正在开发具有 Pages 控制器和两个页面的 Rails3 应用程序:pages#main 和 pages#status。主页有一个链接,单击该链接会进入状态。用户已经有个人资料信息,如果该个人资料信息的一部分不存在,我希望将状态重定向到 main。我得到了一个神秘的双重重定向,但我无法解决。这是页面控制器:
def main
@current_user = current_user
end
def status
@current_user = current_user
if @current_user.address.blank?
redirect_to :action => "main" and return
end
end
只要不满足条件,一切都会顺利进行,但一旦满足,我就会收到错误:
在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,并且每个操作最多调用一次。还要注意,redirect和render都不会终止action的执行,所以如果你想在redirect后退出一个action,你需要做一些类似“redirect_to(...) and return”的操作。
确实,redirect_to 被调用了两次(同一行,根据跟踪;不知道为什么)。我想知道这是否是路线问题。这是routes.rb:
match '/main', :to => 'pages#main'
match '/status', :to => 'pages#status'
任何建议将不胜感激。
这里是开发日志:
Started GET "/status" for 127.0.0.1 at Wed Nov 03 21:28:15 -0700 2010
Processing by PagesController#status as HTML
User Load (0.3ms) SELECT "users".* FROM "users" WHERE ("users"."id" = 3) LIMIT 1
Before redirect
Before redirect
Redirected to
Redirected to
Completed in 32ms
AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".):
app/controllers/pages_controller.rb:15:in `status'
app/controllers/pages_controller.rb:15:in `status'
为了解决这个问题,我在status方法中添加了两条调试线,希望能提供一些线索:
logger.debug "Before redirect"
redirect_to :action => "main" and return
logger.debug "After redirect"
因此,在我们到达“重定向到”之前,“重定向之前”行已被命中。然后“重定向到”出现两次,没有目标。顺便说一句,无论是否在重定向行上出现“并返回”,都会发生这种情况。我真的不知道发生了什么。
另外,有趣的是,我在 main 方法中添加了一个调试行。它永远不会被触发。
【问题讨论】:
-
你能解决这个问题吗?我面临的或多或少是一样的……
标签: ruby-on-rails-3