2011-01-09 9 views
2

私はArtcilesControllerが次のような作成アクションを持っているとします。私はrespond_toブロックをどこに置くべきですか?

def create 
    @article = Article.new(params[:article]) 

    respond_to do |format| 
    if @article.save 
     format.html { redirect_to(@article, :notice => "Article created") } 
     format.json { render :show } 
    else 
     format.html { render :new } 
     format.json { render(:json => { :errors => @article.errors }, :status => :not_acceptable) } 
    end 
    end 
end 

同じアクションは、以下のように書くことができる:最初の例ではrespond_toブロックの内部と第二内であれば他のブロックが存在すること

def create 
    @article = Article.new(params[:article]) 

    if @article.save 
    respond_to do |format| 
     format.html { redirect_to(@article, :notice => "Article created") } 
     format.json { render :show } 
    end 
    else 
    respond_to do |format| 
     format.html { render :new } 
     format.json { render(:json => { :errors => @article.errors }, :status => :not_acceptable) } 
    end 
    end 
end 

注意、内の2つのrespond_toブロックが存在します単一のif elseブロックの

私は他のものよりも1つを優先してください。はいの場合、理由は何ですか?それとも、スタイルを選んでそれに固執するのですか?

答えて

3

スタイルだけですが、1つのリクエストに応答し、コントローラのルーティングロジックをモデルに応じて使用しています。レール3に

def create 
    @article = Article.new(params[:article]) 
    respond_to do |format| 
    format.html { 
    @article.save ? redirect_to(@article, :notice => "Article created") : render :new 
    } 
    format.json { 
     @article.save ? render(:show) : render(:json => { :errors => @article.errors }, :status => :not_acceptable) 
    } 
    end 
end 
+0

私はアップしました。 @ article.saveを引き出し、結果を変数に格納することは、私が別のやり方で行うことだけです。もっとドライ – ffoeg

0

respond_withは、上記のように定型コードのため、これを乾燥します。検証が失敗したときにレンダリング編集/新規フォームとエラーメッセージを処理することさえできます。

関連する問題