tommyd456
tommyd456

Reputation: 10703

Rails routes.rb unexpected behaviour

Editing my Rails 4 app routes.rb file and I'm getting unexpected behaviour (unexpected form my point of view anyway).

I'm trying to create a link that updates a booking record. I have created an action in my BookingsController called WITHDRAW ready to handle the update process. I would like the link to pass the booking id and my code for the link is this:

<%= link_to "Withdraw this booking", bookings_withdraw_path(@booking), :confirm => "Are you sure you want to withdraw this booking?", :method => :patch %>

My problem arises when I try and setup the route for this link. If I add the following line to my routes file:

match 'bookings/withdraw/:bid' => 'bookings#withdraw', via: 'patch'

then when I run the rake command to check the routes it shows this:

bookings_withdrawn GET    /bookings/withdrawn(.:format)          bookings#withdrawn
                   PATCH  /bookings/withdraw/:bid(.:format)      bookings#withdraw

As you can see, the WITHDRAW path is part of the one above (WITHDRAWN is a different path by the way). If I remove the /:bid part from the path then it creates it's own path which is what I would expect.

Can someone explain why this is happening?

Upvotes: 0

Views: 98

Answers (2)

zrl3dx
zrl3dx

Reputation: 7869

As I've written in comment, you should add :as option to your route, i.e.:

match 'bookings/withdraw/:bid' => 'bookings#withdraw', via: 'patch', as: 'bookings_withdraw'

Named route probably wasn't autogenerated because of dynamic part :bid, AFAIK Rails aren't generating implicitly named routes in such cases, so you have to add them explicitly, but I still can't find it in an docs, maybe if somebody've got and can share so I'll update my answer.

Upvotes: 0

Sachin Singh
Sachin Singh

Reputation: 7225

try this out

in you routes file pass a block to resources :bookings like this

  resources :bookings do
    member do
      patch :withdraw
    end
  end

and remove this

match 'bookings/withdraw/:bid' => 'bookings#withdraw', via: 'patch'

Upvotes: 1

Related Questions