While building a Rails app with Bootstrap, I wanted to create a button that showed a product. Here’s the code I used:
<%= button_to 'Show', product, class: 'btn btn-primary' %>
The code was valid but returned a routing error when the button was clicked. Mystifying, as I was using resources for routing. To confirm I wasn’t going insane, I undid my changes and the following was working:
<%= link_to 'Show', product %>
How Did I Fix This?
After some quick Googling, I found out that
button_to defaults to the
POST method. Furthermore, Bootstrap buttons don’t need to be html
<button> elements, they can be standard
<%= link_to 'Show', product, class: 'btn btn-primary' %>
Simply changing from
link_to used the
GET method and a set of
<a> tags. Combined with Bootstrap button styling, I had a nice little button that went to the product. This is the solution I used.
<%= button_to 'Show', product, class: 'btn btn-primary', method: :get %>
This option specifies the use of the
GET method and produces a
<button> with the same styling as above. However, this method is not recommended unless a
<button> is absolutely necessary.