Optimizing Rails Applications with Active Record.
ActiveRecord is the Object-Relational Mapping (ORM) layer used in Ruby on Rails, providing an interface to interact with the database. It acts as a bridge between Ruby objects and database tables, allowing developers to work with database records as if they were regular Ruby objects. This approach simplifies database interactions and enforces the Model-View-Controller (MVC) architecture.
An object which carries both data and behavior, wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data. Much of this data is persistent and needs to be stored in a database. Active Record uses the most obvious approach, putting data access logic in the domain object. This way all people know how to read and write their data to and from the database.
Key Features of ActiveRecord:
-
Database Abstraction: Automatically handles SQL generation and database operations.
-
Migrations: Provides a way to modify the database schema over time.
-
Associations: Defines relationships between tables (e.g.,
belongs_to
,has_many
). -
Validations: Ensures data integrity before saving to the database.
-
Callbacks: Allows executing logic before or after record changes.
-
Query Interface: Provides a rich API for constructing database queries.
Basic Querying Methods
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
all
: Retrieves all records from a table.find
: Retrieves a record by its primary key.where
: Filters records based on specified conditions.order
: Orders records based on specified attributes.limit
andoffset
: Restricts the number of records returned and specifies the starting point for retrieval, respectively.
Example: Retrieving All Records.
# Query
User.all
# Output
[[#<User id: 1, email: "[email protected]", age: 59, created_at: "2025-05-14 10:54:15.357661000 +0000", updated_at: "2025-05-15 16:48:04.097762000 +0000" >,
#<User id: 2, email: "[email protected]", age: 23 created_at: "2025-05-15 16:42:51.860049000 +0000", updated_at: "2025-05-15 16:51:51.970813000 +0000">,
#<User id: 3, email: "[email protected]", age: 51 created_at: "2025-05-16 06:51:55.074272000 +0000", updated_at: "2025-05-16 06:51:55.074272000 +0000"]]
Finding a Single Record
user = User.find(1) # Finds by primary key
user_by_email = User.find_by(email: "[email protected]")
Filtering Records
adults = User.where("age >= 18")
recent_users = User.where("created_at > ?", 1.week.ago)
Ordering Records
ordered_users = User.order(created_at: :desc)
Limiting and Offsetting Results
skip_first_two = User.offset(2).limit(5)