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

mik*_*gto 6 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
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*evo 7

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

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

    render :show
  end
end
Run Code Online (Sandbox Code Playgroud)

图片/路径没有必要.你可以更深入地了解: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
Run Code Online (Sandbox Code Playgroud)

  • **这是正确的答案.**一个值得注意的是:调用`render'show'`*只渲染show template*,它不会调用show动作.因此,如果你的`show`动作中存在实例变量,那么你必须在你的`latest`动作中设置它们,或者在渲染`show`模板的任何其他动作中设置它们. (2认同)

Ben*_*ger 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
Run Code Online (Sandbox Code Playgroud)

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

来源就在这里.