Goal

You’ll be able to use ActiveRecord’s basic query methods confidently, and understand what ActiveRecord actually is — the mechanism that lets Ruby objects represent database rows without writing raw SQL.

Learn

ActiveRecord is Rails’ Object-Relational Mapping (ORM) layer — it lets you interact with database records using plain Ruby objects and methods, rather than writing raw SQL directly:

class Product < ApplicationRecord
end

Product.all                    # all products
Product.find(5)                # find by primary key, raises error if not found
Product.find_by(name: "Book")  # find first match, returns nil if not found
Product.where(price: 10..50)   # all matching a condition, returns a collection
Product.create(name: "Pen", price: 2.50)  # create and save a new record

A model class inheriting from ApplicationRecord automatically gets all of this behavior, with zero manual SQL required — this connects directly to Part 1.1’s convention: the Product class automatically maps to the products table.

A genuinely important distinction: find raises an error (ActiveRecord::RecordNotFound) if no matching record exists, while find_by simply returns nil instead. This matters for how you write calling code — find assumes the record genuinely should exist (an error is the correct signal if it doesn’t), while find_by treats “not found” as a normal, expected possibility your code should handle gracefully, not crash on.

Decision Task

You write Product.find(999) where no product with id 999 exists. Before reading on: what happens, compared to what would happen with Product.find_by(id: 999) instead?

Show Answer

Product.find(999) raises an ActiveRecord::RecordNotFound error, crashing the request unless explicitly handled. Product.find_by(id: 999) instead simply returns nil, letting your code check for that case gracefully (like an if statement) rather than needing to handle an exception. The choice between them signals whether “not found” is expected to be a genuine error or a normal possibility in your specific situation.

Common Mistake

Using find when a record genuinely might not exist as a normal part of your application’s flow, causing unhandled crashes on a completely expected “not found” case. If “not found” is a normal possibility (like a user-supplied search), find_by (returning nil, checked gracefully) is usually the better fit than find (which assumes the record should exist and raises an error otherwise).

Practice Questions

1. Write ActiveRecord code that finds all Product records with a price greater than 100.

Show Answer

Product.where("price > ?", 100)

2. What’s the key behavioral difference between find and find_by when no matching record exists?

Show Answer

find raises an ActiveRecord::RecordNotFound error; find_by simply returns nil instead.

3. Write ActiveRecord code that creates a new Order record with a total of 49.99.

Show Answer

Order.create(total: 49.99)

4. True or False: ActiveRecord requires you to write raw SQL for basic operations like finding or creating records.

Show Answer

False — ActiveRecord lets you use plain Ruby methods for these common operations, without writing raw SQL directly.

5. If “not found” is a completely normal, expected possibility in your specific use case, would find or find_by generally be the better choice?

Show Answer

find_by — since it returns nil gracefully rather than raising an error, better matching a situation where “not found” isn’t genuinely exceptional.

Try It Yourself

Without looking back, write ActiveRecord code that finds the first Customer whose email is “test@example.com”, correctly handling the case where no such customer exists without crashing.

Show Answer

customer = Customer.find_by(email: "test@example.com")\nif customer\n # use customer\nend — using find_by specifically because “not found” is a normal, expected possibility here, not a genuine error.

Quick Check

1. What is ActiveRecord?

Show Answer

Rails’ Object-Relational Mapping (ORM) layer, letting you interact with database records using Ruby objects and methods.

2. What does Product.all return?

Show Answer

All records in the products table.

3. What happens when find can’t locate a matching record?

Show Answer

It raises an ActiveRecord::RecordNotFound error.

4. What happens when find_by can’t locate a matching record?

Show Answer

It returns nil.

5. What must a model class inherit from to get ActiveRecord’s behavior?

Show Answer

ApplicationRecord

تحميل هذا الباب / Download this Chapterنسخة كاملة للدراسة بدون إنترنت، مع الأسئلة والإجابات والصور المتاحة.