Search code examples
ruby-on-railsrubycustom-routes

How do I add different types of GET routes that require parameters in Ruby on Rails


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.


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"