What is the main cause of the N+1 query problem in Rails ActiveRecord?
Think about what happens when you access related data inside a loop.
The N+1 query problem happens when Rails loads the main records first, then runs one query per associated record inside a loop, causing many queries. This happens when you don't use eager loading.
includes vs joinsGiven a Rails model Post with many comments, what is the difference in database queries when using Post.includes(:comments) versus Post.joins(:comments)?
Consider how eager loading and joining affect the number and type of queries.
includes loads the main records and their associations in separate queries to avoid N+1 queries, while joins creates a single query with INNER JOIN combining tables, which can filter results.
select to Optimize QueryWhich option correctly uses select in Rails ActiveRecord to fetch only the id and name columns from the User model?
Remember how to pass multiple columns as symbols or strings in select.
The correct syntax is to pass multiple column names as separate symbols or a single string with comma-separated names. Option A uses symbols correctly. Option A uses a string but with a comma, which is valid in SQL and Rails. Option A misses commas. Option A is invalid syntax.
Given this code snippet, why is the query slow?
users = User.all users.each do |user| puts user.profile.bio end
Think about how accessing associations inside loops affects queries.
Accessing user.profile inside the loop without eager loading causes one query per user to fetch the profile, leading to many queries and slow performance.
pluck and distinctWhat is the output of this Rails code?
Product.where(category: 'books').pluck(:author).uniq
Assuming the database has authors: ['Alice', 'Bob', 'Alice', 'Carol'] in that category.
Remember that pluck returns an array and uniq is a Ruby method applied after fetching.
pluck fetches the author column values as an array including duplicates. uniq is a Ruby method that removes duplicates from the array. So the output is the array with duplicates removed.