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)
render json: UserSerializer.render(@users)
end
For more on information on N+1 queries:
2. Using Map Vs Pluck
Developers of other languages may use the iterator method map
interchangeably with ActiveRecord specific methods such as pluck
. However, the former runs once for each record in the association which requires the entire record set to be loaded in memory while the latter runs a query that returns the desired values directly.
# WRONG
MyModel.all.map(&:my_favorite_attribute)# CORRECT
MyModel.all.pluck(:my_favorite_attribute)