Ruby on Rails: redirect_to not working after create and save
Solution 1
Just replace this part of your code:
if success
flash[:success] = message
redirect_to slider_path
else
flash[:error] = message
end
redirect_to root_path
with this:
if success
flash[:success] = message
redirect_to slider_path
else
flash[:error] = message
redirect_to root_path
end
Solution 2
Rails API states:
An action may contain only a single render or a single redirect. Attempting to try to do either again will result in a DoubleRenderError:
def do_something
redirect_to :action => "elsewhere"
render :action => "overthere" # raises DoubleRenderError
end
If you need to redirect on the condition of something, then be sure to add “and return” to halt execution.
def do_something
redirect_to(:action => "elsewhere") and return if monkeys.nil?
render :action => "overthere" # won't be called if monkeys is nil
end
Note the use of and return
Solution 3
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".
Solution 4
Add a return statement after your redirect. If the action also renders a template by default, any redirects need to be followed by a return statement.
if success
flash[:success] = message
redirect_to slider_path
return # <= Add a return.
else
flash[:error] = message
end
redirect_to root_path
ramz15
Updated on June 27, 2022Comments
-
ramz15 almost 2 years
I want to
redirect_to slider_path
after a user submits their email. Currently, only the success message is displayed without a redirect. Here's the code: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