【问题标题】:Ruby on Rails No route matches [POST]Ruby on Rails 没有路线匹配 [POST]
【发布时间】:2020-08-10 05:39:57
【问题描述】:

我正在尝试维护一些遗留代码,但我很难弄清楚为什么我定义的路线不起作用。

我得到的错误是

Started POST "/api/transactions/weight" ...
ActionController::RoutingError (No route matches [POST] "/api/transactions/weight"):

我的(简化)路线如下

namespace :api do
    resources :transactions, only: [:create] do
        post "weight", to: "transactions#weight"
    end
end

我也尝试过将路线移到resource :transactions 定义之外

namespace :api do
    resources :transactions, only: [:create]

    post "transactions/weight", to: "transactions#weight"
end

但我遇到了同样的错误。我误解了路线定义,还是其他地方的问题?谢谢

【问题讨论】:

  • 问题不在于您的路线。当你有这样的嵌套路由时,你需要传入 transaction_id

标签: ruby-on-rails routes


【解决方案1】:

请务必查看bundle exec rake routes 以了解您的路线。

post 方法将“/weight”路由定义为成员路由(作用于特定的“事务”资源

# bundle exec rake routes

api_transaction_weight POST   /api/transactions/:transaction_id/weight(.:format). api/transactions#weight

默认情况下,如果不指定on: 选项,resources 块内的路由将被创建为成员路由。

您想通过on: :collection将其指定为收集路线[1]

namespace :api do
  resources :transactions, only: [:create] do
    post "weight", to: "transactions#weight", on: :collection
  end
end
# bundle exec rake routes

weight_api_transactions POST   /api/transactions/weight(.:format)  api/transactions#weight

[1]https://guides.rubyonrails.org/routing.html#adding-collection-routes

【讨论】:

    【解决方案2】:

    您定义路由的方式会将“权重”视为成员路由。如果你想将其定义为收集路由。

    namespace :api do
        resources :transactions, only: [:create] do
            collection {post :weight}
        end
    end
    

    上述约定将权重暴露为集合路由而不是成员路由。如果您想定义为成员发布请求。然后使用以下约定

    namespace :api do
        resources :transactions, only: [:create] do
            member {post :weight}
        end
    end
    

    如果您在路由中使用 api.rb 作为绘图文件,那么您需要重新启动应用程序以反映路由文件中的更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-31
      • 1970-01-01
      相关资源
      最近更新 更多