【问题标题】:Get Rails3 to Load Different View让 Rails3 加载不同的视图
【发布时间】: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


【解决方案1】:

Rav,您可以粘贴此请求的开发日志吗?具体来说,对 /status 的第一次请求会导致重定向到 /main,还是会因上述错误而失败?

具体来说,在 log/development.log 中查找最近的一个或多个请求块。

【讨论】:

  • 我已经在日志中粘贴了,上面还有更多信息。感谢您回复我。
  • 我认为 redirect_to 不起作用。不要指定操作,而是尝试“redirect_to(main_url) 并返回”
  • "redirected to" 空白让我相信您的 redirect_to 不起作用。
  • 我在重定向之前放了一个“调试器”行,然后我得到了……两行“重定向到”行打印到日志中。不知道发生了什么。我想我将完全避免这个问题:让它根据条件信息创建原始链接,而不是将其发送到状态并要求重定向。虽然这是一个谜。感谢您的建议。
猜你喜欢
  • 1970-01-01
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
  • 2011-06-01
  • 2015-12-11
  • 1970-01-01
  • 2012-07-25
  • 1970-01-01
相关资源
最近更新 更多