Ruby on Rails - Active Record Basics
Introduction
Active Record is the Object-Relational Mapping (ORM) layer supplied with Rails. It facilitates the creation and use of business objects whose data requires persistent storage to a database. This guide will introduce you to the basics of Active Record and its core functionalities.
Key Points:
- Active Record connects classes to relational database tables to establish an almost zero-configuration persistence layer for applications.
- Active Record includes features for validations, callbacks, and associations.
- This guide covers the basic CRUD operations and how to work with Active Record models.
Creating a Model
To create a model in Rails, you can use the generator command:
# Generate a model named Article with title and body attributes
rails generate model Article title:string body:text
# Run the migration to create the articles table in the database
rails db:migrate
This command creates the model file, a migration file, and test files for the model.
CRUD Operations
Active Record makes it easy to perform CRUD (Create, Read, Update, Delete) operations on your models. Here are examples of each operation:
Create
# Creating a new record
article = Article.new(title: "First Article", body: "This is the body of the first article.")
article.save
# Or using the create method
article = Article.create(title: "Second Article", body: "This is the body of the second article.")
Read
# Finding records
article = Article.find(1)
articles = Article.all
first_article = Article.first
last_article = Article.last
Update
# Updating a record
article = Article.find(1)
article.update(title: "Updated Title", body: "Updated body of the article.")
Delete
# Deleting a record
article = Article.find(1)
article.destroy
Validations
Active Record provides validations to ensure that only valid data is saved into your database. Here is an example of adding validations to a model:
# app/models/article.rb
class Article < ApplicationRecord
validates :title, presence: true, length: { minimum: 5 }
validates :body, presence: true
end
Callbacks
Callbacks are methods that get called at certain moments of an object's life cycle. Here is an example of using callbacks in a model:
# app/models/article.rb
class Article < ApplicationRecord
before_save :set_default_title
private
def set_default_title
self.title = "Default Title" if self.title.blank?
end
end
Associations
Active Record makes working with relationships between models simple and easy. Here are examples of different types of associations:
One-to-Many Association
# app/models/article.rb
class Article < ApplicationRecord
has_many :comments
end
# app/models/comment.rb
class Comment < ApplicationRecord
belongs_to :article
end
Many-to-Many Association
# app/models/author.rb
class Author < ApplicationRecord
has_and_belongs_to_many :books
end
# app/models/book.rb
class Book < ApplicationRecord
has_and_belongs_to_many :authors
end
One-to-One Association
# app/models/user.rb
class User < ApplicationRecord
has_one :profile
end
# app/models/profile.rb
class Profile < ApplicationRecord
belongs_to :user
end
Conclusion
Active Record is a powerful ORM that simplifies database interactions in Rails applications. By understanding the basics of Active Record, including CRUD operations, validations, callbacks, and associations, you can efficiently manage your application's data and business logic.