Databases
Ruby Active Record
Using Active Record
Ruby Active Record maps database queries to objects in Rails.
Introduction to Active Record
Active Record is the Object Relational Mapping (ORM) layer supplied with Rails. It allows developers to interact with a database using Ruby objects rather than SQL. This means you can create, read, update, and delete database entries using Ruby code.
Setting Up Active Record
To use Active Record in a Rails application, you first need to configure your database settings. This is typically done in the config/database.yml
file. Here's an example configuration for a PostgreSQL database:
Defining Models
Models in Rails are classes that inherit from ApplicationRecord
. They represent the structure of the database tables and the relationships between them. Here's an example of a model:
Migrations
Migrations are a feature of Rails that allow you to evolve your database schema over time. Migrations are written in Ruby and can be used to create or modify database tables. Here's an example migration to create an articles table:
Querying the Database
Active Record allows you to run database queries using Ruby methods. Here are some examples:
Article.all
- Retrieves all articles.Article.find(1)
- Finds an article with the ID of 1.Article.where(title: 'Hello World')
- Finds articles with the title 'Hello World'.
Associations
Active Record provides several types of associations to define relationships between models. Here are some examples:
- One-to-Many: A single model can have many of another model. For example, an article can have many comments.
- Many-to-Many: Many models can have many of another model, typically through a join table.
Conclusion
Ruby Active Record is a powerful ORM that simplifies interacting with databases by abstracting SQL into Ruby methods. It supports various database operations and relationships, making it an essential tool in the Rails framework.
Databases
- Active Record
- PostgreSQL
- SQLite
- MongoDB
- Database Transactions
- Previous
- CORS
- Next
- PostgreSQL