2012-11-12 40 views
5

我在我的控制器中有一個latest操作。此操作只抓取最後一條記錄並呈現show模板。Rails 3 respond_with自定義模板

class PicturesController < ApplicationController 
    respond_to :html, :json, :xml 

    def latest 
    @picture = Picture.last 

    respond_with @picture, template: 'pictures/show' 
    end 
end 

是否有更簡潔的方式提供模板?由於這是網站控制器,似乎冗餘必須爲HTML格式提供pictures/部分。

回答

7

如果你想呈現模板,屬於同一個控制器,你可以寫它,就像這樣:

class PicturesController < ApplicationController 
    def latest 
    @picture = Picture.last 

    render :show 
    end 
end 

這是沒有必要的圖片/路徑。你可以去更深的位置:Layouts and Rendering in Rails

如果您需要保存XML和JSON格式,你可以這樣做:

class PicturesController < ApplicationController 
    def latest 
    @picture = Picture.last 

    respond_to do |format| 
     format.html {render :show} 
     format.json {render json: @picture} 
     format.xml {render xml: @picture} 
    end 

    end 
end 
+2

**這是正確的答案**值得注意的一個問題:調用'render'show'' *只渲染顯示模板*,它不會調用顯示操作。因此,如果show show模板需要'show'動作中有實例變量,那麼您必須在''latest'動作中設置這些變量,或者設置其他渲染'show'模板的動作。 – Andrew

+0

查看我的更新。我需要爲此操作保留「API導航」(JSON和XML格式)。我知道我可以給'respond_with'塊,並執行'format.html {render:show}'。這也看起來不像應該那樣乾淨。 – mikeycgto

+0

您如何爲自定義模板執行操作,而不是已經是其他操作的一部分的模板?如何在共享文件夾中定製模板? – ahnbizcad

5

我做同樣這@Dario巴里奧努埃沃,但我需要保存XML & JSON格式,並不喜歡做respond_to區塊,因爲我試圖使用respond_with響應者。原來你可以做到這一點。根據需要對JSON & XML

class PicturesController < ApplicationController 
    respond_to :html, :json, :xml 

    def latest 
    @picture = Picture.last 

    respond_with(@picture) do |format| 
     format.html { render :show } 
    end 
    end 
end 

默認行爲將運行。您只需指定您需要覆蓋的一種行爲(HTML響應),而不是全部三種。

Source is here