Today, we will be walking through how to create a Rails backend API utilizing a postgresql database. This will be a simple way to start a project that may be complex!
🌞 Let's get started 🌞
In your base directory of your terminal, you can create a project directory using this command:
Look! First step already done. Now, let's change directories so that we will be inside the project. Input this into the terminal:
Cool! Let's move onto the good stuff...
While remaining in your project directory, we are going to generate the Rails application using:
rails new project_backend_name_here --api --database=postgresql
Toward the end of our command, we "flag" an api and "flag" a postgresql-based database. These two flags will help us to create and store data.
Using the "rails new" generator gave us a ton of stuff. Our backend includes, most notably:
- an "app" folder that houses our Model-View-Controller (MVC) structure.
- a "db" folder that houses our database migrations, schema, and seed file.
- a "config" folder that houses a routes file, environment file, and initializers folder, etc.
Next, we can go to our terminal and run:
Simply, this creates our database. From here, you can now start creating migrations.
Command lines like ⤵️ will generate a whole MVC structure for that resource.
rails g resource User name, email, password
Whereas, command lines like ⤵️ will only generate the model structure.
rails g model User name, email, password
Or, command lines like ⤵️ will only generate the controller structure.
rails g controller User
Whatever you may choose, always migrate after each created migration. We can do this using:
This will ultimately finalize your migrations and set up your schema.
From here, you may add seed data, add many more resources, install gems... the list can go on forever.
While this may be an oversimplified explanation of creating a Rails backend API, I find it necessary indulge in. Everyone has a starting point to their education and career in tech, so why not help?
🌞Feel free to comment below!
🌞Feedback + questions are welcome.
🌞As always, let's learn together<3