我希望在用户提交电子邮件后redirect_to slider_path
。目前,仅显示成功消息而没有重定向。这是代码:
class Splash::SubscribersController < ApplicationController
def create
@subscriber = Subscriber.new(params[:subscriber])
if @subscriber.save
success = true
message = "Success! We'll let you know when we launch."
else
success = false
message = "Fail."
end
respond_to do |format|
format.html {
if success
flash[:success] = message
redirect_to slider_path
else
flash[:error] = message
end
redirect_to root_path
}
format.json { render :json => { :success => success, :message => message }.to_json }
end
end
end
答案 0 :(得分:6)
操作可能只包含一个渲染或一个重定向。尝试再次尝试将导致DoubleRenderError:
def do_something
redirect_to :action => "elsewhere"
render :action => "overthere" # raises DoubleRenderError
end
如果你需要重定向某事的条件,那么一定要添加“并返回”以停止执行。
def do_something
redirect_to(:action => "elsewhere") and return if monkeys.nil?
render :action => "overthere" # won't be called if monkeys is nil
end
请注意使用and return
答案 1 :(得分:6)
只需替换这部分代码:
if success
flash[:success] = message
redirect_to slider_path
else
flash[:error] = message
end
redirect_to root_path
用这个:
if success
flash[:success] = message
redirect_to slider_path
else
flash[:error] = message
redirect_to root_path
end
答案 2 :(得分:2)
重定向后添加一个return语句。如果该操作在默认情况下也呈现模板,则任何重定向都需要后跟一个return语句。
if success
flash[:success] = message
redirect_to slider_path
return # <= Add a return.
else
flash[:error] = message
end
redirect_to root_path
答案 3 :(得分:2)
重定向和渲染都不会终止执行操作,因此如果您想在重定向后退出操作,则需要执行类似“redirect_to(...)并返回”的操作。