Get Rails3 to Load Different View
I'm working on a Rails3 app that has a Pages controller, and two pages: pages#main and pages#status. The main page has a link which, when clicked, goes to status. The user already has profile information, and if part of that profile information is not present, I want status to redirect to main. I'm getting a mysterious double-redirect though, that I can't solve. Here's the pages controller:
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
Everything works swimmingly as long as the condition isn't met, but as soon as it is, I get the error:
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".
Indeed, redirect_to is called twice (same line, according to the trace; not sure why). I'm wondering whether it is a routes problem. Here is routes.rb:
match '/main', :to => 'pages#main'
match '/status', :to => 'pages#status'
Any suggestions would be greatly appreciated.
Here is the development log:
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'
Trying to solve the problem, I've added two debugging lines to the status method, in the hopes that it will provide some clue:
logger.debug "Before redirect"
redirect_to :action => "main" and return
logger.debug "After redirect"
So, the "Before redirect" lines are hit before we get to "Redirected to". Then "Redirected to" appears twice with no target. Incidentally, this happens with or without "and return" on the redirect line. I'm really not sure what's going on.
Also, interestingly, I added a debug line to the main method. It is never triggered.
Rav, can you paste the development log for this request? Specifically, does the first request for /status result in a redirect to /main, or does it fail with the above error?
Specifically, look in log/development.log for the most recent request block or blocks.
精彩评论