为什么使用资源时 Rails routes.rb 中的顺序很重要?

Why does order matter in Rails routes.rb when using resources?

当我的路线如此列出时,我收到一条错误消息:

resources :coupons
get 'coupons/redeem_coupon', to: 'coupons#redeem_coupon', as: 'redeem_coupon'

错误是:

ActiveRecord::RecordNotFound - Couldn't find Coupon with 'id'=redeem_coupon:

当我将顺序反转为:

get 'coupons/redeem_coupon', to: 'coupons#redeem_coupon', as: 'redeem_coupon'
resources :coupons

它工作正常。我知道资源创建了这些路线

GET /coupons
GET /coupons/new    
POST    /coupons    
GET /coupons/:id    
GET /coupons/:id/edit   
PATCH/PUT   /coupons/:id        
DELETE  /coupons/:id    

是先列​​出我的自定义路线,更具体还是覆盖其他路线?为什么顺序很重要?

通过首先列出您的自定义路线,您将覆盖其他路线。当 rails 收到请求时,它只是从您的 routes.rb 文件的顶部开始,然后使用最先匹配的路由。

您收到的错误是因为 rails 尝试从上到下匹配路由。如果您尝试向现有资源添加自定义路由,则更简单的方法是执行此操作。 collection 是如果你想在组上使用它,member 是如果你想将自定义路由添加到单个资源。

resources :coupons do
  collection do
    get 'redeem_coupon'
  end
end