2011-01-09 49 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 

相同的動作可以寫成像也下列:

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 

請注意,在第一個例子中是有respond_to代碼塊的內部和第二一個if else塊,有內部的兩個的respond_to塊一個if else塊。

我應該比其他人更喜歡嗎?如果是的話,有什麼原因?或者只是選擇一種風格並堅持使用它的問題?

回答

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

我upvoted。只有我會做不同的事情是將@ article.save取出並將結果存儲在變量中。更幹 – ffoeg

0

在導軌3 respond_with將如上述乾燥該起來,爲樣板代碼。它甚至在驗證失敗時處理渲染編輯/新窗體和錯誤消息。