RoR Models and ActiveRecord

Models are the data layer of your Rails application. They represent real-world objects — like users, products, or orders — and connect them to rows in a database table. Rails uses a library called ActiveRecord to handle all database communication automatically.

What ActiveRecord Does

ActiveRecord is the bridge between your Ruby objects and your database tables. You never write raw SQL to fetch or save data. Instead, you call Ruby methods and ActiveRecord translates them into SQL behind the scenes.

You write Ruby:          Article.all
ActiveRecord runs SQL:   SELECT * FROM articles
You get back:            An array of Article objects
You write Ruby:          article.save
ActiveRecord runs SQL:   INSERT INTO articles (title, body) VALUES (...)
Database stores:         One new row in the articles table

The Model ↔ Database Mapping

Ruby Class         Database Table     Columns
------------------------------------------------------
Article            articles           id, title, body, created_at
User               users              id, name, email, created_at
Product            products           id, name, price, stock
OrderItem          order_items        id, order_id, product_id, qty

Convention: Model = singular, Table = plural
  Article model  →  articles table
  User model     →  users table
  OrderItem      →  order_items table

Creating a Model

Generate a model with the Rails generator:

rails generate model Article title:string body:text published:boolean

This creates two files:

app/models/article.rb                        ← the Ruby class
db/migrate/20240101_create_articles.rb       ← the database migration

The model file starts simple:

app/models/article.rb

class Article < ApplicationRecord
end

That's it. By inheriting from ApplicationRecord, your Article model automatically gets all ActiveRecord features — find, save, update, delete, and more.

Run the Migration

The model exists in Ruby, but the table does not exist in the database yet. Run the migration to create it:

rails db:migrate

Rails creates the articles table with columns: id, title, body, published, created_at, updated_at.

CRUD with ActiveRecord

Create

Article.create(title: "Hello World", body: "My first post.", published: true)

# Or in two steps:
article = Article.new(title: "Hello World", body: "My first post.")
article.save

Read

Article.all                    # All articles
Article.find(1)                # Article with id = 1
Article.find_by(title: "Hello World")   # First match
Article.where(published: true) # All published articles
Article.first                  # First record by id
Article.last                   # Last record by id

Update

article = Article.find(1)
article.update(title: "Updated Title")

# Or update one attribute:
article.title = "New Title"
article.save

Delete

article = Article.find(1)
article.destroy        # Deletes the record and triggers callbacks

Article.destroy(1)     # Shortcut — same result

Scopes — Named Queries

Scopes let you define reusable queries inside your model:

class Article < ApplicationRecord
  scope :published, -> { where(published: true) }
  scope :recent, -> { order(created_at: :desc).limit(5) }
  scope :by_title, -> (keyword) { where("title LIKE ?", "%#{keyword}%") }
end

Use them in your controller:

Article.published          # All published articles
Article.recent             # Last 5 articles
Article.by_title("Rails")  # Articles with "Rails" in title
Article.published.recent   # Chain them together

Model Methods

Add custom methods to your model to keep logic in one place:

class Article < ApplicationRecord
  def short_body
    body.truncate(150)
  end

  def reading_time
    words = body.split.size
    "#{(words / 200.0).ceil} min read"
  end

  def published_label
    published? ? "Live" : "Draft"
  end
end

Use these anywhere in your app:

article.short_body       # First 150 characters of body
article.reading_time     # "3 min read"
article.published_label  # "Live" or "Draft"

Callbacks

Callbacks run automatically at specific points in a record's life cycle:

class Article < ApplicationRecord
  before_save   :set_slug
  after_create  :send_notification
  before_destroy :archive_record

  private

  def set_slug
    self.slug = title.downcase.gsub(" ", "-")
  end
end

Common callbacks:

CallbackWhen It Runs
before_validationBefore Rails checks validations
after_validationAfter validation passes or fails
before_saveBefore any save (create or update)
after_createAfter a new record is created
before_destroyBefore a record is deleted

ActiveRecord Diagram

Your Code
  Article.create(title: "Post 1")
        |
        v
ActiveRecord (in app/models/article.rb)
  Runs before_save callbacks
  Runs validations
  Translates to SQL
        |
        v
Database (SQLite / PostgreSQL)
  INSERT INTO articles (title) VALUES ("Post 1")
        |
        v
ActiveRecord returns the saved Article object
        |
        v
Your Code has the saved article with its new id

ActiveRecord removes the need to write SQL. You interact with data using plain Ruby, and Rails handles the database layer completely.

Leave a Comment

Your email address will not be published. Required fields are marked *