Setting MySQL database to Rails Application

MySQL is an open-source relational database management system. In this post I’m going to explain to use MySQL database to rails project. Install MySQL database if you do not have installed MySQL databse to your system.When you create new rails project with following command, it will add SQLite gem to the Gemfile, which is for SQLite database.

rails new project_name

Or you can directly specify the database when create new rails project. For this mysql2  gem should be install to the current ruby version. For this run following command:

gem install mysql2

Then,

rails new project_name -d mysql

Which will initially add mysql2 gem to your Gemfile.

Change the directory to project directory with following command:

cd project_name

If mysql2 gem is not exists in Gemfile, you have to change this gem from Gemfile.

gem 'mysql2'

And install bundle with following command:

bundle install

After this you have to setup your database configuration in database.yml

development:
  adapter: mysql2
  database: db_name_development
  username: root
  password: root_password
  host: 127.0.0.1

test:
  adapter: mysql2
  database: db_name_test
  username: root
  password: root_password
  host: 127.0.0.1

Here we configure only for development and test environment. For development environment:

  • db_name_development is database name in MySQL for development environment.
  • root is MySQL root user. You can use different username for different user.
  • root_password is password for root user.

After complete configuration we need to run following rake/rails command. Which will create database in MySQL database.

rake db:create

New we have database db_name_development is ready but we do not have any table in database. We have to generate model or migration to add tables in this database. For example, I need to create a table called books, then I have to generate model called Book which generates migration to create books table. Migration file looks like:

rails g model Book name:string isbn:string cost:float

This commannd generate Book model in which you can see in app/models directory and migration file like below in db/migrations directory.

class CreateBooks < ActiveRecord::Migration
 def change
    create_table :books do |t|
     t.string :name
     t.string :isbn
     t.float :cost
     t.timestamps null: false
    end
 end
end

After this we have to run following command to create books table in database.

rake db:migrate

Which will create table books with following column.

id, name, isbn, cost, created_at and updated_at
0Shares

Leave a Reply

Your email address will not be published. Required fields are marked *