Skip to content

Instantly share code, notes, and snippets.

@ssaunier
Created March 2, 2020 14:59
Show Gist options
  • Save ssaunier/a2bf840db1de3e05b4ab7a49e02b7db8 to your computer and use it in GitHub Desktop.
Save ssaunier/a2bf840db1de3e05b4ab7a49e02b7db8 to your computer and use it in GitHub Desktop.
Creating a Rails app with MySQL database after Le Wagon

If you graduated from Le Wagon, you know how to create a Rails Application using a PostgreSQL database.

What if you want to use MySQL instead?

You are on the right page! here is a quick tutorial on how to do it, on macOS (for Linux, MySQL setup is different, follow along this tutorial and then follow along starting with rails new [...])

brew install mysql
# For a quick start, do not put a `root` password yet.
mysql.server start

Now let's install the latest version of mysql2 gem. On macOS, it needs some help:

gem install mysql2 -v '0.5.3' -- --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include

Time to generate the Rails app:

cd ~/code/$YOUR_USERNAME
rails new rails-mysql-example --database mysql
cd rails-mysql-example

You can have a look at the Database configuration and see we are using mysql instead of pg here:

cat config/database.yml

That's in that file where you'll put user/password configuration in case you secure your local database install.

Let's scaffold an Article model:

rails db:create
rails g scaffold Article title:string content:text
rails db:migrate

Now let's start the server:

rails s

And go to http://localhost:3000/articles. Hooray! You should be able to CRUD articles directly in your new MySQL databasae. Mission accoplished!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment