Ruby on Rails — How To Route To Edit Method With A “button_to” Helper

Laurence Hawelu
2 min readApr 29, 2021

Have you ever wanted to use a button to expose an edit route but received an error about matching routes? Well, this is something that I recently experienced and wanted to get to the bottom of what caused it. This blog will go into detail about why this happened and how to fix it.

Let’s say we have a model for pets that has the following columns: name and breed. We have already created our show view but would like to have a button on this page that will route us to our edit form.

However, with this current code after we click the edit button we receive the error below:

We have the correct route, but based on the error it looks like it is thinking this is a POST when in reality it should be a GET. Let’s look at the element in our development tools to see what the HTML is for this button:

Interestingly, it looks like the option listed under the method tag is POST. Now that we have identified the issue, let’s take a look at the documentation for the button_to helper. Since we have identified the issue as an incorrect method we can focus our attention on the method section of the documentation:

  • :method — Symbol of HTTP verb. Supported verbs are :post, :get, :delete, :patch, and :put. By default it will be :post.

It looks like the :method associated with the button_to helper is the POST verb by default. That being said, since :method is an option for the button_to helper we can refactor our code to resolve this problem. Below is the updated code:

With this knowledge you will now be able to use the button_to helper for any of the following verbs: post, get, delete, patch, and put!

References: https://apidock.com/rails/ActionView/Helpers/UrlHelper/button_to

--

--