I have a latest
action in my controller. This action just grabs the last record and renders the show
template.
class PicturesController < ApplicationController
respond_to :html, :json, :xml
def latest
@picture = Picture.last
respond_with @picture, template: 'pictures/show'
end
end
Is there a cleaner way to supply template? Seems redundant to have to supply the pictures/
portion for the HTML format since this is the Sites controller.
If the template you want to render, belongs to the same controller, you can write it just like this:
class PicturesController < ApplicationController
def latest
@picture = Picture.last
render :show
end
end
It is not necessary the pictures/ path. You can go deeper here: Layouts and Rendering in Rails
If you need to preserve xml and json formats, you can do:
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
I've done this similarly to @Dario Barrionuevo, but I needed to preserve XML & JSON formats and wasn't happy with doing a respond_to
block, since I'm trying to use the respond_with
responders. Turns out you can do this.
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
The default behavior will run as desired for JSON & XML. You only have to specify the one behavior you need to override (the HTML response) instead of all three.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.