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

I get an error when my route is indicated as such:

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

Error:

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

When I cancel the order:

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

It works great. I understand that resources create these routes.

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

Is enumerating my custom route the first, more specific, or overriding another route? Why does order matter?

+4
source share
2 answers

The error you get is that the rails try to map routes starting from the top level. If you are trying to add a custom route to an existing resource, the easiest way to do this. collection , if you want to use it in a group, member is if you want to add a custom route to a separate resource.

 resources :coupons do collection do get 'redeem_coupon' end end 
+3
source

By listing your route first, you redefine another route. When the rails receive the request, it just starts at the top of your routes.rb and goes depending on which route matches the first.

+2
source

All Articles