Search code examples
ruby-on-railsrestroutesnested-resources

Rails routes generate Post request for New action in nested resources


I have the following nested resources:

  resources :listings do
    resources :offers do
     member do
       put "accept"
       put "reject"
     end
   end
 end

In my listings/show.html.haml, I have

= button_to "Make Offer", new_listing_offer_path(@listing)

Now, when I click button, rails generate a POST request, and thus an error:

Started POST "/listings/2/offers/new" for 127.0.0.1 
ActionController::RoutingError (No route matches "/listings/2/offers/new"):

If I refresh (GET request), then the page displays correctly.

I believe this incorrect routing only happens when I added two extra actions: accept and reject, which happens to be POST actions.

Is it a bug in Rails, or it is my fault? How should I prevent this error?

Thank you.


Solution

  • The button_to helper creates a form for you which by default will send a POST request to the URL you've specified ("/listings/2/offers/new").

    The routing you've specified will not generate a route to handle a POST request to /new. You can inspect your generated routes and the verbs to which they will respond by running the "rake routes" task.

    If you are looking to merely link to the form, change your "button_to" to a "link_to" and add CSS for aesthetics.

    = link_to "Make Offer", new_listing_offer_path(@listing)
    

    (this GET would route to your OfferController's new action)

    If you are looking to actually POST data, you will likely need to change your usage to:

    = button_to "Make Offer", listing_offers_path(@listing)
    

    (this POST would route to your OfferController's create action.)