繁体   English   中英

Rails 3使用自定义模板进行响应

[英]Rails 3 respond_with custom template

我的控制器中有latest动作。 此操作只是抓取最后一条记录并呈现show模板。

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

  def latest
    @picture = Picture.last

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

是否有更清洁的方式来提供模板? 似乎冗余必须提供HTML格式的pictures/部分,因为这是Sites控制器。

如果要渲染的模板属于同一个控制器,则可以像这样编写:

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

    render :show
  end
end

图片/路径没有必要。 你可以更深入地了解: 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

我和@Dario Barrionuevo的做法类似,但是我需要保留XML和JSON格式,并且不喜欢做一个respond_to块,因为我正在尝试使用respond_with响应器。 事实证明你可以做到这一点。

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

默认行为将根据JSON和XML的需要运行。 您只需指定需要覆盖的一个行为(HTML响应)而不是全部三个。

来源就在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM