How to share a view between formats with Rails

Viewed 46

I have a Rails controller which provides both HTML and PDF responses, and thus I have view.pdf.haml and view.html.haml files. These are either identical or extremely close to identical.

How can I have Rails use a single view for multiple formats?

2 Answers

Do you mean have the same action serve up different resource types - i.e. both a web page and a PDF? If I understand the problem, you can use the respond_to method.

def show
  @object = Object.find params[:id]

  respond_to do |format|
    format.html
    format.pdf { ..code to render the pdf.. }
  end
end

That ..code to render the pdf.. is the tricky part. There are PDF gems that support inline rendering, but you may end up using send_data or similar to set a file name, disposition, etc and deliver the PDF document to the end user.

Related