Question

I have a list of users being displayed, you can click on "Show user" or "PDF" to see details of that user in HTML or as a PDF document. The show was automatically created with scaffolding, now I'm trying to add the option to view it as a PDF. The problem is adding a second GET option, if I pass the user along as a parameter, it is assumed to be a POST and I get an error that the POST route does not exist. I am not trying to update the user, just to show it in a different way, basically to add a second "show user" option.

How do I tell it that I want a GET, not a POST? Is there an easier way to do what I am trying to do? Thanks.

Was it helpful?

Solution

Please, create a controller like this:

class ClientsController < ApplicationController
  # The user can request to receive this resource as HTML or PDF.
  def show
    @client = Client.find(params[:id])

    respond_to do |format|
      format.html
      format.pdf { render pdf: generate_pdf(@client) }
    end
  end
end

Please, update route.rb file, action name with post and get, like below :

match 'action_name', to: 'controller#action', via: 'post'
match 'action_name', to: 'controller#action', via: 'get'

More info please read this link : "http://guides.rubyonrails.org/routing.html"

OTHER TIPS

you haven't posted any code or details, so I am guessing you want something like this:

routes

resources :users

controller

class UsersController < ActionController::Base
  def show
   @user = User.find(params[:id])
   respond_to do |format|
        format.html # show.html.erb
        format.pdf    # handle the pdf response
    end
  end
end

view file in views/users/show.pdf.prawn

prawn_document() do |pdf|
    @user.each {|r| pdf.text r.id} # will print user id of the user
end

The way above example will work is, if something visits the following URLs, they will get html file:

localhost:3000/users/1 #html is the default format in rails
localhost:3000/users/1.html

but if they visit .pdf, they will be served a pdf format.

localhost:3000/users/1.pdf

If the above assumptions are correct, then check prawn or wicked_pdf pdf gem. the above example uses prawn

Checkout this link http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to. You can add a new MIME type and pass on the :format as pdf in all your rails routes.

Hope this will help.

And for the POST-request check your config/routes.rb There shoud be a few routes already, so you can infer the route you need.

In your link you can pass an additional parameter called format for pdf. For e.g.

<%= link_to 'Display in PDF', "/user/pdf", :format => "pdf" %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top