Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: redirect_to not working after create and save

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
like image 465
ramz15 Avatar asked Jan 13 '12 18:01

ramz15


2 Answers

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
like image 84
alexkv Avatar answered Nov 16 '22 15:11

alexkv


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

like image 6
Simon Bagreev Avatar answered Nov 16 '22 17:11

Simon Bagreev