Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

ruby on rails - redirect_to != return

I'm looking for some clarification regarding the behaviour of redirect_to.

I have this code:

if some_condition
   redirect_to(path_one)
end

redirect_to(path_two)

If some_condition == true I get this 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.

It seems that the method continues to execute after the redirect_to call. Do I need to write code like this:

if some_condition
   redirect_to(path_one)
   return
end

redirect_to(path_two)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you need to return from method when doing redirect. It actually only adds appropriate headers for the response object.

You can write more rubyish way:

if some_condition
    return redirect_to(path_one)
end

redirect_to(path_two)

or other way:

return redirect_to(some_condition ? path_one : path_two)

or another way:

redirect_path = path_one

if some_condition
    redirect_path = path_two
end

redirect_to redirect_path

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...