Ruby on Rails: SQlite3 to PostgreSQL
For a couple of my projects I used Ruby on Rails as an API and by default it sets your database as SQlite3. You can set up a PostgreSQL database when creating your backend through the command line but if you’re like me you tend to forget small things. So, I’ll run through how to create your Ruby On Rails API backend with PostgreSQL and how to change your database from SQlite3 to PostgreSQL if you’ve already started a project.
CREATING YOUR API BACKEND WITH POSTGRESQL
When creating your API, you’ll want to run the following command line.
You’ll notice that you’ll initiate your project as you would normally but we add a couple of extra things. Lets’s break it down.
- “- -api” gets rid of the unnecessary functions of a normal ruby on rails application. ApplicationController also inherits from ActionController::API instead of ActionController::Base.
- “-T” generates the app without any test files.
- “- -database=postgresql” tells your application to use postgresql instead of sqlite3. Self explanatory.
If you’re like me and you’ve realized you’ve forgotten to add the last requirement then you’ve initialized your project with an sqlite3 database. So lets change that.
SWITCHING FROM SQLITE3 TO POSTGRESQL
At this point, you might be feeling overwhelmed and you’ve done all this programming just to realize you’re using the wrong database. Good news is you don’t have to start from scratch. This is an easy three step process.
- Updating the Gemfile
Currently in your Gemfile, you’ve installed sqlite3 by default. Let’s change that gem file to postgresql or “pg”.
2. Update config/database.yml
This file will look like this by default.
You will want to change it to this! Don’t mind the comments. Your focus should be on the development and test portions of this code. It’s important to note that the “database:” keys have a value of the name of your project + “_development” under development or + “_test” under test. So if my app were called “pokemon-api”, my development would be “database: pokemon-api_development” and “pokemon-api_test” for the test.
3. Migrate
Almost done! The last thing is to run “rails db:migrate” in your command line and start up a new server to make sure everything is running smoothly! Don’t forget to commit your changes to github.
SUMMARY
That’s it! So lets run it back and go over it. Change your Gemfile to the appropriate gem you need. Update the config/database.yml file and then migrate your changes. Lastly, run a server and check to see that everything is running as intended. As always, happy coding!
Huge thanks to Victoria Crawford because she heavily influenced this blog. I’ll post her article down below as she explains how to switch from these two databases in more detail.
https://dev.to/torianne02/making-the-change-from-sqlite3-to-postgresql-ruby-on-rails-2m0p