0
0
Ruby on Railsframework~20 mins

Database query optimization in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rails Query Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Understanding N+1 Query Problem in Rails

What is the main cause of the N+1 query problem in Rails ActiveRecord?

AUsing eager loading with <code>includes</code> to preload associations
BLoading associated records inside a loop without eager loading
CQuerying the database only once for all records
DUsing raw SQL queries instead of ActiveRecord methods
Attempts:
2 left
💡 Hint

Think about what happens when you access related data inside a loop.

component_behavior
intermediate
2:00remaining
Effect of Using includes vs joins

Given a Rails model Post with many comments, what is the difference in database queries when using Post.includes(:comments) versus Post.joins(:comments)?

A<code>includes</code> loads only posts; <code>joins</code> loads only comments
B<code>includes</code> performs an INNER JOIN; <code>joins</code> loads posts and comments separately
C<code>includes</code> loads posts and comments in separate queries; <code>joins</code> performs an INNER JOIN returning combined rows
D<code>includes</code> and <code>joins</code> both perform the same single query with LEFT JOIN
Attempts:
2 left
💡 Hint

Consider how eager loading and joining affect the number and type of queries.

📝 Syntax
advanced
2:00remaining
Correct Use of select to Optimize Query

Which option correctly uses select in Rails ActiveRecord to fetch only the id and name columns from the User model?

AUser.select(:id, :name)
BUser.select('id name')
CUser.select('id, name')
DUser.select(:id name)
Attempts:
2 left
💡 Hint

Remember how to pass multiple columns as symbols or strings in select.

🔧 Debug
advanced
2:00remaining
Identifying Cause of Slow Query in Rails

Given this code snippet, why is the query slow?

users = User.all
users.each do |user|
  puts user.profile.bio
end
ABecause <code>profile.bio</code> is a method, not a database column
BBecause <code>User.all</code> loads too many users at once
CBecause <code>puts</code> slows down the loop
DBecause <code>profile</code> association is not eager loaded, causing N+1 queries
Attempts:
2 left
💡 Hint

Think about how accessing associations inside loops affects queries.

state_output
expert
2:00remaining
Output of Query with pluck and distinct

What 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.

A['Alice', 'Bob', 'Carol']
B['Alice', 'Bob', 'Alice', 'Carol']
C['Alice', 'Bob', 'Carol', 'Alice']
D['Alice', 'Bob']
Attempts:
2 left
💡 Hint

Remember that pluck returns an array and uniq is a Ruby method applied after fetching.