4 Mistakes to Avoid as a RoR Engineer
Ruby on Rails is a powerful framework that if used properly can speed up development and provide a strong foundation for a scalable application. However, some simple mistakes can quickly make Rails a burden.
1. Forgetting to Check for N+1 Queries
N+1 occurs when a record collection is retrieved without loading its required associations. This leads to 1 query to fetch the original collection and N queries to fetch the association of each record. This causes a slowdown due to an unnecessarily large number of DB roundtrips. Instead, we should eager load the first query so we can make a single larger query (with the ID of all elements in association) to fetch the associated records. A great way to check for N+1 queries and get suggestions on how to fix them is the Bullet gem.
Model
class User < ApplicationRecord
has_one :picture
end
Serializer
class UserSerializer < ApplicationSerializer
identifier :id
fields :name, :username, :created_at
association :picture, blueprint: PictureSerializer
end
Controller
# WRONG
def index
@users = User.all
render json: UserSerializer.render(@users)
end# CORRECT
def index
@users = User.all.includes(:picture)…