How to Use MySQL Database with Ruby on Rails

How to Use MySQL Database with Ruby on Rails

Using MySQL with Ruby on Rails involves configuring the database, creating models, and performing CRUD (Create, Read, Update, Delete) operations. Here are the steps to get started:

1. Create a New Rails Application:

Bash
rails new myapp -d mysql

This command creates a new Rails application with MySQL as the database.

2. Configure the Database:

Open the config/database.yml file and make sure the development and test sections are configured for MySQL:

YAML
development:
  adapter: mysql2
  database: myapp_development
  username: root
  password: password
  host: localhost

test:
  adapter: mysql2
  database: myapp_test
  username: root
  password: password
  host: localhost

Replace myapp_development and myapp_test with your actual database names. Also, update the username and password with your MySQL credentials.

3. Create a Model:

Generate a model using the Rails generator. This will create a corresponding database table and model file.

Bash
rails generate model Product name:string description:text price:decimal

4. Migrate the Database:

Run the migration to create the corresponding database table.

Bash
rails db:migrate

5. Interacting with the Database:

Open the Rails console to interact with the database.

Bash
rails console

6. Perform CRUD Operations:

Create:

Ruby
product = Product.new(name: 'Product 1', description: 'Description 1', price: 10.99)
product.save

Read:

Ruby
Product.all
Product.find(1)
Product.where(price: 10.99)

Update:

Ruby
product = Product.find(1)
product.price = 12.99
product.save

Delete:

Ruby
product = Product.find(1)
product.destroy

7. View the Application:

Start the Rails server:

Bash
rails server

Visit http://localhost:3000 in your browser to see your application.

Important Notes:

  • Ensure your MySQL server is running.
  • Rails follows convention over configuration, so make sure your model and database table names are pluralized and follow Rails naming conventions.
  • Use migrations to manage changes to your database schema over time.

By following these steps, you can start using MySQL with Ruby on Rails for building web applications. Remember to replace placeholders like myapp, Product, and field names with your actual values.

Total
0
Shares

Leave a Reply

Previous Post
How to Use MySQL Database with Node.js

How to Use MySQL Database with Node.js

Next Post
How to Set up MySQL Database Workbench

How to Set up MySQL Database Workbench

Related Posts