Search code examples
javascriptjqueryruby-on-railsajaxjrubyonrails

No Route Matching in rails 6 for multiple route parameters


routes.rb:

get '/get_text_by_tablenum/:filename_id/:tablenum_id', to: 'dashboard#get_text_by_tablenum'

ajax:

$.ajax({
      dataType: "json",
      cache: false,
      url: '/get_text_by_tablenum/' + filename + '/' + id_value_string,
      timeout: 5000,
      error: function(XMLHttpRequest, errorTextStatus, error) {
       alert("Failed to submit : " + errorTextStatus + " ;" + error);

      },
      success: function(data) {
        console.log(data)


      }

rake routes:

GET /get_text_by_tablenum/:filename_id/:tablenum_id(.:format)  dashboard#get_text_by_tablenum

ERROR MESSAGE:

No route matches [GET] "/get_text_by_tablenum/MPLX_1Q20_Conf_Call_Slides.pdf/12"

any thoughts on why I'm getting this error message?


Solution

  • It's simple your resource must be at the end of the URL. MPLX_1Q20_Conf_Call_Slides.pdf it is a file and not a path.

    example:

    get "path/to/file.pdf", to: "my_controller#action"`
    

    The dot was removed because it is used as a separator for formatted routes. If you need to use a dot within an :filename add a constraint. constraints: { filename: /.*/ }

    Now your routes look like this:

      get 'files/:filename', to: "files#index", constraints: { filename: /.*/ }
    

    then in browser: http://localhost:3000/files/MPLX_1Q20_Conf_Call_Slides.pdf

    files_controller.rb

    app/controllers/files_controller.rb
        1: class FilesController < ApplicationController
        2:   def index
        3:     byebug
    =>  4:     filename = params[:filename]
        5:     send_file("#{Rails.root}/private/#{filename}",
        6:           :filename => "#{filename}",
        7:           :type => "application/pdf", #for example if pdf
        8:           :disposition => 'inline')
        9:   end
       10: end
    (byebug) params
    <ActionController::Parameters {"controller"=>"files", "action"=>"index", "filename"=>"MPLX_1Q20_Conf_Call_Slides.pdf"} permitted: false>