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:
rails new myapp -d mysqlThis 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:
development:
adapter: mysql2
database: myapp_development
username: root
password: password
host: localhost
test:
adapter: mysql2
database: myapp_test
username: root
password: password
host: localhostReplace 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.
rails generate model Product name:string description:text price:decimal4. Migrate the Database:
Run the migration to create the corresponding database table.
rails db:migrate5. Interacting with the Database:
Open the Rails console to interact with the database.
rails console6. Perform CRUD Operations:
Create:
product = Product.new(name: 'Product 1', description: 'Description 1', price: 10.99)
product.saveRead:
Product.all
Product.find(1)
Product.where(price: 10.99)Update:
product = Product.find(1)
product.price = 12.99
product.saveDelete:
product = Product.find(1)
product.destroy7. View the Application:
Start the Rails server:
rails serverVisit 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.