Rails ActiveRecord: Basics
I was recently interviewing for a React developer position, and the questions were in-depth — they asked me to expand in detail, which I…
Rails ActiveRecord: Basics
I was recently interviewing for a React developer position, and the questions were in-depth — they asked me to expand in detail, which I was thankfully able to explain in decent terms because I had written articles about JavaScript and React before. So I decided to write articles about Rails to fortify my understanding of its many topics, since teaching is the best way to learn.
If you’re curious why I’m writing about things that are simple and easy to learn online, consider these my own study notes.
The What
It’s Ruby on Rails’s implementation of the ORM (Object-Relational Mapping) pattern. ActiveRecord is a layer that maps Ruby classes (models) to database tables, where each class instance represents a row in the table, allowing you to read, edit, and delete records by calling Ruby methods.
The Why
An ORM lets you store and retrieve an object’s attributes — and the relationships between objects — without writing SQL by hand (see the Rails Guides on Active Record Basics for the canonical description). In practice, that means you can access records, join tables, and query data using Ruby methods instead of raw SQL.
Retrieving
Consider the following SQL query to get the users who have active posts:
SELECT u.* FROM users u
JOIN posts p ON p.user_id = u.id
WHERE p.status = 'active';
In ActiveRecord, this becomes:
User.joins(:posts).where(posts: { status: 'active' })
Updating
Updating a record in SQL looks like this:
UPDATE books
SET price = 9, title = 'Animal Farm'
WHERE id = 1;
which translates to:
Book.find(1).update(price: 9, title: 'Animal Farm')
Deleting
Deleting a record in SQL:
DELETE FROM books WHERE id = 1;
translates to:
Book.find(1).destroy
The How
Let’s take the books table as an example. Inside the app/models folder, create a file book.rb with the following:
class Book < ApplicationRecord
end
There are three things to notice here.
1 — The class name (UpperCamelCase)
Rails converts the model’s class name to snake_case and pluralizes the last word to find the matching database table, so a class named Book matches a table named books. For classes that contain multiple words, it goes like this:
BookClub => book_clubs
BookAuthorsClub => book_authors_clubs
Note that only the last word is pluralized — it’s book_authors_clubs, not books_authors_clubs. A handy way to check how a class name resolves to a table name is tableize:
'BookAuthorsClub'.tableize
# => "book_authors_clubs"
2 — Inheriting from ApplicationRecord
ApplicationRecord is the base class for all models, and it inherits from ActiveRecord::Base, which is what turns a regular Ruby class into an ActiveRecord model.
3 — Namespacing and directory
We placed our file directly in the app/models folder, but there are cases where you'll want to namespace a class under a specific module:
# app/models/book/order.rb
class Book::Order < ApplicationRecord
end
This file goes in app/models/book/order.rb. One thing that surprises people: by default this model maps to the orders table, not book_orders — ActiveRecord ignores the namespace when deriving the table name. If you actually want the book_orders table, you have to opt in, either by setting a prefix on the namespace module:
# app/models/book.rb
module Book
def self.table_name_prefix
'book_'
end
end
or by naming the table explicitly on the model:
# app/models/book/order.rb
class Book::Order < ApplicationRecord
self.table_name = 'book_orders'
end
What Lives Inside
Inside a model, you usually define three things.
Validations
ActiveRecord lets you validate a record’s data before it’s written to the database. These validations run before methods like save, create, and update.
class Book < ApplicationRecord
validates :title, presence: true
end
book = Book.new
is_saved = book.save
puts is_saved # => false
puts book.errors.full_messages # => ["Title can't be blank"]
Callbacks
ActiveRecord lets you hook into events in a model’s lifecycle — validation, saving, creation, updating, destruction, and commit.
# A commit is the final step of a database transaction — think of it as "finishing".
## before_<lifecycle_step>
# before_validation
# before_save
# before_create
# before_update
# before_destroy
# before_commit
## around_<save | create | update | destroy>
## after_<validation | save | create | update | destroy | commit>
class Book < ApplicationRecord
after_create :publish
private
def publish
puts 'book published!'
end
end
Associations
ActiveRecord lets you establish relationships between models by declaring associations. For example, an author has many books:
class Author < ApplicationRecord
has_many :books
end 메타데이터
- post_id
- 47ec52f90e56
- slug
- rails-activerecord-basics-47ec52f90e56
- url
- https://medium.com/@abdoamin/rails-activerecord-basics-47ec52f90e56
- canonical_url
- https://medium.com/@abdoamin/rails-activerecord-basics-47ec52f90e56
- author_url
- https://medium.com/@abdoamin
- status
- ok
- fetched_at
- 2026-06-16 19:09:56