2012-01-13 20 views
5

ユーザがメールを送信した後にredirect_to slider_pathしたいです。現在、リダイレクトなしで成功メッセージのみが表示されます。コードは次のとおりです。Ruby on Rails:作成して保存した後にredirect_toが機能しない

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 

答えて

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

リダイレクト後にリターンステートメントを追加します。デフォルトでアクションがテンプレートをレンダリングする場合、リダイレクトにはreturn文が必要です。

if success 
    flash[:success] = message 
    redirect_to slider_path 
    return     # <= Add a return. 
else 
    flash[:error] = message 
end 
redirect_to root_path 
6

Rails API状態:

アクションが唯一のレンダリング単一または単一のリダイレクトが含まれていてもよいです。 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

2

リダイレクトもなく、アクションの実行を終了レンダリングどちらをしたがって、リダイレクト後にアクションを終了するには、liを実行する必要があります"redirect_to(...)"を返してください。

関連する問題