6

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

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

  def latest
    @picture = Picture.last

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

有没有更简洁的方式来提供模板?pictures/由于这是站点控制器,因此必须提供 HTML 格式的部分似乎是多余的。

4

2 回答 2

7

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

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
于 2012-11-12T15:04:19.263 回答
6

我的做法与@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 响应),而不是全部三种。

来源在这里

于 2013-12-03T21:52:22.980 回答