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.
There are a variety of ways to customize the behavior of render. You can render the default view for a Rails template, or a specific template, or a file, or inline code, or nothing at all. You can render text, JSON, or XML. You can specify the content type or HTTP status of the rendered response as well.
In broad strokes, this involves deciding what should be sent as the response and calling an appropriate method to create that response. If the response is a full-blown view, Rails also does some extra work to wrap the view in a layout and possibly to pull in partial views.
From the controller's point of view, there are three ways to create an HTTP response: You've heard that Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes.
If you try to render content along with a non-content status code (100-199, 204, 205, or 304), it will be dropped from the response. Rails uses the format specified in the request (or :html by default). You can change this passing the :formats option with a symbol or an array:
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.
Source is here.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With