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控制器.
如果要渲染的模板属于同一个控制器,则可以像这样编写:
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)
我和@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响应)而不是全部三个.