Setting up a Rails API Backend

Our migration file should look likeLastly we need to create a migration for our list items table..This table will have a name, quantity, status and will belong to a list..Our migration file should look likeWith the migration files ready to go, there is one last thing to do before moving on to the next step..Running the following command rake db:migrate will instruct Rails to run the migration files and create the tables and columns in the database.The next step of creating a Rails API is setting up the models, we will be starting with the User model..Navigate to the model folder, it is nested under the app folder in the root of the directory..In the model folder we need to create a user.rb file to house our User model..In order to have Rails work its magic, each model file will need to contain a class of the same name..The User model file should look likeLine 3 tells Rails to not make a new User unless a username and email is provided..Line 4 tells Rails to make sure the username and email provided are unique before creating a new user..Line 5 is provided by the bcrypt gem and will encode the password provided by the user so it is not stored as a plain string in the database..This is important in case the database ever gets hacked; otherwise, a hacker will have easy access to a user’s email and password and most people reuse the same password on numerous sites..Line 6 informs Rails that there is a relationship between the User and List model and that each User can have many lists.We will setup our List and ListItem models in the same folder and following the same conventions as when we created our User model.. More details

Leave a Reply