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

时间:2012-11-12 14:51:16

标签: ruby-on-rails ruby-on-rails-3

我的控制器中有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/部分,因为这是站点控制器。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:6)

我和@Dario Barrionuevo的做法类似,但我需要保留XML&amp; 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&amp; XML。您只需指定需要覆盖的一个行为(HTML响应)而不是全部三个。

Source is here

相关问题