2012-11-12 44 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