【问题标题】:How to replace 'show' with 'download' in rails routes?如何在 Rails 路线中用“下载”替换“显示”?
【发布时间】:2023-03-14 13:36:01
【问题描述】:

这快把我逼疯了。 Rails 说我没有定义控制器动作,但我显然在 rake routes 中定义了。

我在这里错过了什么?

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

没有路由匹配动作的失败消息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 路线 | grep 文件:

     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}

【问题讨论】:

  • 您是否在您的API::V1::FilesController 中定义了公共方法download
  • 还没有,正在尝试 TDD 这个东西。
  • 不确定,但如果您改用to: "files#download"(复数),也许您的方式也可以。

标签: ruby-on-rails ruby routes


【解决方案1】:

您可以使用这样的块向资源添加更多路由:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
  • 2016-10-31
  • 2013-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多