Setting Up Database for your Ruby on Rails Application

Setting Up Database for your Ruby on Rails Application

Rails ships with sqlite3 as the default database. Chances are you won't want to use it because it's stored as a simple file on disk. You'll probably want something more robust like MySQL or PostgreSQL.

There is a lot of documentation on both, so you can just pick one that seems like you'll be more comfortable with.

You need to have a working Ruby on Rails Development in order to create rails applications. See the instruntions here

Database Option- 1 (Setting Up MySQL)

You can install MySQL server and client from the packages in the Ubuntu repository. As part of the installation process, you'll set the password for the root user. This information will go into your Rails app's database.yml file in the future.

sudo apt-get install mysql-server mysql-client libmysqlclient-dev

Installing the libmysqlclient-dev gives you the necessary files to compile the mysql2 gem which is what Rails will use to connect to MySQL when you setup your Rails app.

Database Option -2 (Setting Up PostgreSQL)

For PostgreSQL, we're going to add a new repository to easily install a recent version of Postgres.

sudo sh -c "echo 'deb http://apt.postgresql.org/pub/repos/apt/ xenial-pgdg main' > /etc/apt/sources.list.d/pgdg.list"
wget --quiet -O - http://apt.postgresql.org/pub/repos/apt/ACCC4CF8.asc | sudo apt-key add -
sudo apt-get update
sudo apt-get install postgresql-common
sudo apt-get install postgresql-9.5 libpq-dev

The postgres installation doesn't setup a user for you, so you'll need to follow these steps to create a user with permission to create databases. Feel free to replace john with your username.

sudo -u postgres createuser john -s

# If you would like to set a password for the user, you can do the following
sudo -u postgres psql
postgres=# \password john

Final Steps

And now for the moment of truth. Let's create your first Rails application:

If you want to use SQLite (not recommended)

rails new myapp	

If you want to use MySQL

rails new myapp -d mysql

If you want to use Postgres

Note that this will expect a postgres user with the same username as your app, you may need to edit config/database.yml to match the user you created earlier

rails new myapp -d postgresql

Move into the application directory

cd myapp

Now create the application database

rails db:create

& then start the server

rails server

You can now visit http://localhost:3000 to view your new website!

Now that you've got your machine setup, it's time to start building some Rails applications.If you received an error that said Access denied for user 'root'@'localhost' (using password: NO) then you need to update your config/database.yml file to match the database username and password.