Best Practices for Active Record Models

Tutorial 5 of 5

Best Practices for Active Record Models

1. Introduction

In this tutorial, we're going to discuss the best practices for using Active Record models in Rails. Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic.

Goals of the tutorial:

  • Understand how to structure your models in Rails.
  • Learn how to make your application more efficient, maintainable, and scalable.

Prerequisites:

Basic knowledge of Ruby on Rails and Active Record is required.

2. Step-by-Step Guide

Keep your models skinny

A good practice is to keep your models 'skinny'. This means having only the methods needed for database transactions. If a method does not interact with the database, it should probably be in the controller.

# Bad
class User < ActiveRecord::Base
  def full_name
    "#{first_name} #{last_name}"
  end
end

# Good
class User < ActiveRecord::Base
end

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    @full_name = "#{@user.first_name} #{@user.last_name}"
  end
end

Avoid callbacks for complex logic

Callbacks can make testing and debugging difficult. Instead, consider using service objects or other methods to handle complex logic.

# Bad
class User < ActiveRecord::Base
  before_save :encrypt_password

  def encrypt_password
    # complex encryption logic
  end
end

# Good
class User < ActiveRecord::Base
end

class EncryptPasswordService
  def initialize(user)
    @user = user
  end

  def call
    # complex encryption logic
  end
end

3. Code Examples

Using scopes for common queries

Scopes are a way to define common queries that you can reference later.

# Bad
def self.verified
  where(verified: true)
end

# Good
scope :verified, -> { where(verified: true) }

Validate presence of associated objects

# Bad
class Order < ActiveRecord::Base
  belongs_to :customer

  def place
    raise 'Customer is required' unless customer.present?
    # ...
  end
end

# Good
class Order < ActiveRecord::Base
  belongs_to :customer
  validates :customer, presence: true
end

4. Summary

In this tutorial, we've learned about best practices for using Active Record models in Rails, including keeping your models skinny, using scopes for common queries, and validating the presence of associated objects.

5. Practice Exercises

  1. Create a User model with first_name and last_name attributes. Write a method to return the full name of the user.

  2. Add a verified attribute to the User model. Write a scope to return all verified users.

  3. Create an Order model that belongs to User. Validate the presence of User when an Order is created.

Remember, the key to mastering these concepts is practice. Keep coding and it'll become second nature.

Additional Resources