The Active Record pattern helps you work with your database easily by connecting your data to simple objects. It lets you save, find, and update data without writing complex database code.
0
0
Active Record pattern in Ruby on Rails
Introduction
When you want to create, read, update, or delete data in a database using simple Ruby objects.
When building a web app that needs to store user information, like sign-up details.
When you want to keep your database code organized and easy to understand.
When you want to link database tables to Ruby classes automatically.
When you want to use built-in methods to query and manage data without writing SQL.
Syntax
Ruby on Rails
class ModelName < ApplicationRecord # Your code here end
Each model class represents a table in the database.
Model instances represent rows in that table.
Examples
This creates a User model linked to the users table.
Ruby on Rails
class User < ApplicationRecord
endThis creates a new user object and saves it to the database.
Ruby on Rails
user = User.new(name: "Alice", email: "alice@example.com") user.save
This finds a user by ID, changes their email, and saves the update.
Ruby on Rails
user = User.find(1) user.email = "new_email@example.com" user.save
Sample Program
This example shows how to create, find, update, and display a product using Active Record.
Ruby on Rails
class Product < ApplicationRecord end # Create a new product product = Product.new(name: "Book", price: 15.99) product.save # Find the product by id found_product = Product.find(product.id) # Update the product price found_product.price = 12.99 found_product.save # Output product details puts "Product: #{found_product.name}, Price: $#{found_product.price}"
OutputSuccess
Important Notes
Active Record automatically maps class names to table names (e.g., Product to products).
Use migrations to create or change database tables safely.
Always call save to store changes in the database.
Summary
Active Record connects Ruby classes to database tables for easy data handling.
It lets you create, read, update, and delete data using simple Ruby code.
It helps keep your database work clean and organized without writing SQL.