Viking Code School Week 4: Rails and Star Wars

The highlight of the week was Thursday’s Hackathon, where we had 6 hours to deploy a working Rails application. The only requirement was that we use the Star Wars API. I decided to build a Star Wars-themed Tripadvisor, using the API to get information about planets in the Star Wars universe as well as to create random reviews by Star Wars characters.

In order to have a review site, I needed places (or in this case, planets) to review. Rails has a ‘seeds’ feature that makes it easy to set up the database of a blank application. I grabbed the name, population, climate and terriain from the first ten planets from the Star Wars API. My index page showed a list of the planet names each with a link to more information about the planet.

With planets to review, I needed a way for visitors to write reviews. I could use HTML <form> and <input> tags, but here Rails provides a helper method called ‘form_for’. Pass in a resource and form_for will take care of creating a nicely structured ‘params’ hash and routing that information to the correct controller action. For my reviews, I wanted a rating (1–5), a title, an author name, and a review.

When it comes to forms that take user input, validation is always a good idea. In Rails, we can set up validations in the model. I used validations to make sure all the fields were filled out, that the body of the review was at least 20 characters and that the rating was between 1 and 5. If all these conditions are met, the review is saved to the database and the user is redirected to that planet’s page. If something is missing, the user is sent back to the new review form and an error message is displayed.

With planets to review and a way for users to write reviews, I had the basic functionality of a trip review site. With the time remaining, I added some sorting capabilities. “Top Rated” would show the top 5 planets ranked by average rating, while “Deserts”, “Forests”, and “Mountains” would show planets with that kind of terrain.

Going from zero to a deployed application over the course of a day was a great experience. It’s also incredible to think about how much has changed since I first attempted to learn Rails a few months ago by stumbling through the Jumpstart Blogger tutorial. That said, I know that there is still a lot of Rails to learn and I can’t wait to keep exploring! Oh, and if you’re planning your next galactic vacation, be sure to check out Star Wars Trips advisor.