Loosen Up Those Buttons
The Ones in Rails, Not Your Clothing
Author’s Note: I named this blog before I remembered how risqué the song and video for “Loosen Up My Buttons” actually were. Sticking with it.
Buttons are beautiful! They’re fabulous! They’re functional, but can also be used to add flair to your favorite bits of clothing! They’re the unsung hero of the fashion industry, and should be praised for their loyalty despite the rise of the zipper.
Much like clothing, buttons in Rails are functional, are fabulous to work with, and can make our views beautiful. While Rails won’t do much to make the buttons beautiful on its own, the buttons allow us to provide much cleaner views to our users.
At this point, I know you’re probably wondering why do we need to “loosen up” something that seems so… perfect? Well, life is full of surprises. Surprise: Perfection isn’t real! Even our friendly neighborhood buttons have their flaws. Let’s fix them.
Buttons ALWAYS Want to Post
Imagine you’ve taken a wrong turn, and now you’re stuck between a rolling boulder and some sort of hard place (maybe a wall?). The boulder’s rolling at a pretty slow pace, but you’re bound to be crushed unless you can get out of the way. You’re trying to climb your way out, but you can’t find anything to grip. Luckily for you, someone comes and pulls you out, but they just kind of leave you there. You’re safe, but you haven’t gone anywhere and you still can’t get where you were trying to go.
This is similar to what happens when we use a button for anything other than a POST request.
<%= button_to "Add a Song", new_song_path %>
The code above will allow us to leave our point of origin, but we’ll get an error on the server:
The button_to helper’s method is inherently set to POST, but in this case, we’re sending a GET request. To fix this, we can just update the method in our code to match the HTTP verb for our route.
<%= button_to "Add a Song", new_song_path, method: :get %>
By updating the method, we tell our view to look for the controller action that matches our path helper and to perform the corresponding action. We can follow the same steps if we’re using a button to delete an instance, too.
<%= button_to "Delete Song", @song, method: :delete %>
Note: If you’re running Capybara tests, note that use of button_to will appear as a form to Capybara.
By default, buttons will be grey and black, so not very exciting. If you’re ready to move on to styling, checkout some of the handy resources below!
Add Style To Your Rails App With Materialize
Not sure how to add style to your Rails application? Up until a few days ago, I wasn’t sure either! Luckily for us…
Quickly design and customize responsive mobile-first sites with Bootstrap, the world's most popular front-end open…