Open In App

How to Connect MySQL with Ruby on Rails?

Last Updated : 01 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Connecting MySQL to Ruby on Rails enables developers to leverage the powerful relational database management capabilities of MySQL within their Rails applications. This process involves installing MySQL and Rails, configuring the database settings, and setting up the necessary gems. By integrating these technologies, developers can efficiently manage database operations and execute SQL queries seamlessly.

Connecting MySQL

1. Install MySQL

Ensures your package list is up-to-date and install the MySQL server package the MySQL development libraries using the below commands.

sudo apt update
sudo apt install mysql-server
sudo apt-get install libmysqlclient-dev
Install MySQL

Start the MySQL server using the below command.

sudo systemctl start mysql

2. Install Rails

First insure that you have Ruby installed on your system. You can install Rails using RubyGems package manager.

gem install rails

Set up a new Rails app configured for MySQL, this command will change the default database to MySQL. Then get to your working directory.

rails new myapp -d mysql
cd myapp
Create new rails app

3. Configure Database

Edit 'myapp/config/database.yml' with MySQL credentials and specifies database connection settings for your Rails app.

development:
adapter: mysql2
encoding: utf8
reconnect: false
database: myapp_development
pool: 5
username: <your_username>
password: <your_password>
host: localhost

4. Install Gem

Install the 'mysql2' gem which is helpful for working with MySQL in Rails applications.

gem install mysql2
Install mysql2 Gem

5. Create and Migrate the Database

Set up the MySQL database for your Rails environment and run the database migrations.

rails db:create
rails db:migrate

6. Run SQL Queries from Terminal

Now you can run MySQL queries from command by logging in to your account.

mysql -u <user_name> -p

Next Article
Article Tags :

Similar Reads