Rails 3 “No route matches” error and _method

Since last few days, I am enjoying programing on RoR. But, yesterday, I became cracked for a stupid error. I wrote a route in rails 3 and it matched properly. But I was getting a error: “No route matches”. Opps, I guess you didn’t understand the error. Let me explain it briefly.

I created the route as following

match '/verify'=> 'products#verify', :as => :verify, :via => :post

And I wanted to use this route in the edit form. And, so, I set form action = “/verify” by verify_path and form method=”post”. But, unfortunately, I was getting error No route matches [PUT] “/verify”. Somehow, my post request becomes put.

So, I had to dig couple of hours to figure out the exact problem. It’s pretty interesting. Basically, rails follows the REST structure. But, not all browsers supports PUT and DELETE requests. Rails is a bit smart here. In order to handle this types of request rails use _method parameter. If you use form_for, it will add a hidden element as below though the form method is post.

<input name="_method" type="hidden" value="put" />

For delete link:

<a href="/products/1" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Delete</a>

By this, _method parameter, it decides the HTTP verb and routes to appropriate action. I added another link for delete, where rails uses the html5 data-method to wire up JavaScript events to send the delete request to the server.
happy hacking 🙂

 

Eftakhairul Islam

Hi, I'm Eftakhairul Islam, a passionate Software Engineer, Hacker and Open Source Enthusiast. I enjoy writing about technical things, work in a couple of startup as a technical advisor and in my spare time, I contribute a lot of open source projects.

 

One thought on “Rails 3 “No route matches” error and _method

  1. nice findings and sharing.

    yes, this is way around of the browsers that does not support required http methods used by rails

    you can write your route shortly like:

    post ‘/verify’=> ‘products#verify’, :as => :verify

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Read previous post:
Compile a Linux kernel from source

I always like to do something in Linux. Although my plan is a bit different. Right now I don't want...

Close