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.
Basic knowledge of Ruby on Rails and Active Record is required.
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
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
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) }
# 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
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.
Create a User
model with first_name
and last_name
attributes. Write a method to return the full name of the user.
Add a verified
attribute to the User
model. Write a scope to return all verified users.
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.