So What’s a CRUD? It stands for Create, Read, Update, and Destroy. Our PokeDex needs to allow the user to add Pokemon to their Pokedex, edit them, and delete them. It should also let the user see which pokemon they have added. Our app will also have a sign up and a login that uses the bcrypt gem to protect user passwords. If that all makes sense then lets go ahead and jump in.
For this project we are using Sinatra and ActiveRecord, along with SQLite3. We will run our server on the localhost:9393 port using the Shotgun Gem.
In this project we are using the corneal gem. It’s the bomb.com, so if you are getting familiar with Sinatra, go ahead and get acquainted with this gem. In the above picture you can see that our file structure is all neatly tucked inside of a folder named “app”. Corneal will take care of this for you. It uses the MVC (model, view, controller) structure to make use of ActiveRecord. You can also see in the above picture, that we have two helper methods that will make our lives easier in the future.
Once we have our shotgun server running, we’ll make our way over to localhost:9393. This will make a get request to our program at ‘/’. In the above picture you can see
get "/" do
This line of code is going to take us to a .erb file in our views folder called welcome. There we will have all of the HTML we want to display when the user reaches this page. Our welcome page will display the login screen and include a navbar to allow a new user to sign up.
A couple pictures up you can see our helper methods. We will use those to find the current user using sessions, and to check if the user is logged in. Once our user has signed up and/or logged in, they will be rerouted to the main PokeDex, where they will have the option to add Pokemon to their account.
Above we can see the code that will loop through our Pokemon objects and determine whether or not they belong to the current user. (We are using the sytnax <%%> and <%=%> to use ruby logic in our HTML forms.) If they don’t, we will display the Pokemon’s number, name, sprite and a button to capture them. If they do belong to the user, the same information will be displayed, but with a button to release them.
Once a user has added Pokemon to his PokeDex, he can navigate to the “Your Pokemon” page and view all of the Pokemon he has captured. Here the user can view Pokemon stats, edit their names, and release them.
Here we see our code for the Update and Delete portion of our crud. We are using a PokemonTrainer model as a join table for our Pokemon and Trainer models. Using this model allows us to Associate The trainer and the pokemon without having to create new objects for them. Instead we create a PokemonTrainer object that has the ID for both the Pokemon and the Trainer. Using this logic, its easy to Destroy or Update the associate. Simply find the object using the ID’s and alter it.