binarymason binarymason - 3 months ago 10
Ruby Question

How to replace 'show' with 'download' in rails routes?

This is driving me crazy. Rails is saying I don't have a controller action defined, but I clearly do in

rake routes
.

What am I missing here?

spec/controllers/api/v1/files_controller_spec.rb:

describe "download action" do
after do
get :download, id: file.id
end

it "returns http status 200 OK" do
expect(response).to have_http_status(200)
end
end


Failure message of no route matches action
download
:


Failures:

1) Api::V1::FilesController download action returns http status 200 OK
Failure/Error: get :download, id: file.id

ActionController::UrlGenerationError:
No route matches {:action=>"download", :controller=>"api/v1/files", :id=>"2"}


config/routes.rb:

namespace :api, defaults: { format: :json } do
namespace :v1 do
resources :files, only: [:index, :create]
get "files/:id", to: "file#download", as: "file"

end
end


rake routes | grep file:

api_v1_files GET /api/v1/files(.:format) api/v1/files#index {:format=>:json}
POST /api/v1/files(.:format) api/v1/files#create {:format=>:json}
api_v1_file GET /api/v1/files/:id(.:format) api/v1/file#download {:format=>:json}

Answer

You can add more routes to a resource with a block like so:

resources :files, only: [:index, :create] do
  member do 
    get 'download'
  end
end
Comments