Bird
Raised Fist0
Ruby on Railsframework~20 mins

Joins and includes in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rails Joins & Includes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does this ActiveRecord query return?
Consider these models: Author has_many books. What does this query return?
Author.joins(:books).where(books: {published: true}).distinct
AAll authors including those without any books, filtered by published books.
BAll authors and their books, regardless of published status.
CAll authors who have at least one published book, without duplicates.
DAll books that are published, including their authors.
Attempts:
2 left
💡 Hint
Think about what joins and where do together.
❓ state_output
intermediate
2:00remaining
What is the SQL query generated by this Rails code?
Given Post.includes(:comments).where(comments: {approved: true}), what kind of SQL query does Rails generate?
AOne query for posts only, ignoring comments filter.
BOne query for posts and comments with a LEFT OUTER JOIN, filtering approved comments.
COne query for posts, and a separate query for approved comments (two queries total).
DA single SQL INNER JOIN query joining posts and comments with approved filter.
Attempts:
2 left
💡 Hint
Remember how includes works with conditions on associated tables.
🔧 Debug
advanced
2:00remaining
Why does this query raise an error?
This code raises an error:
User.includes(:profile).where(profiles: {active: true})

Why?
ABecause <code>includes</code> does not support conditions on included tables without <code>references</code>.
BBecause <code>profiles</code> table does not exist in the database.
CBecause <code>includes</code> always uses INNER JOIN which conflicts with the condition.
DBecause <code>where</code> cannot filter on associated tables at all.
Attempts:
2 left
💡 Hint
Think about how Rails handles conditions on included associations.
📝 Syntax
advanced
2:00remaining
Which option correctly eager loads and filters associated records?
You want to load all Order records with their items, but only items with status: 'shipped'. Which code is correct?
AOrder.joins(:items).where(items: {status: 'shipped'}).includes(:items)
BOrder.eager_load(:items).where(items: {status: 'shipped'})
COrder.includes(:items).where(items: {status: 'shipped'}).references(:items)
DOrder.includes(:items).where(items: {status: 'shipped'})
Attempts:
2 left
💡 Hint
Consider which method forces a JOIN and eager loads in one query.
🧠 Conceptual
expert
3:00remaining
What is the main difference between joins and includes in Rails?
Choose the best explanation of the difference between joins and includes:
A<code>joins</code> performs an INNER JOIN in SQL and returns records matching the join condition; <code>includes</code> eager loads associations to avoid N+1 queries, using separate queries or LEFT OUTER JOIN.
B<code>joins</code> always loads associated records in separate queries; <code>includes</code> always uses INNER JOIN to filter records.
C<code>joins</code> and <code>includes</code> are interchangeable and produce the same SQL queries.
D<code>joins</code> loads all associated records regardless of conditions; <code>includes</code> filters associated records using INNER JOIN.
Attempts:
2 left
💡 Hint
Think about how each method affects SQL and loading behavior.

Practice

(1/5)
1. What is the main purpose of using joins in Rails ActiveRecord queries?
easy
A. To update multiple tables at once
B. To preload associated records to avoid extra database queries
C. To combine tables and filter records based on matching columns
D. To delete records from multiple tables

Solution

  1. Step 1: Understand what joins does

    joins connects tables in a query to filter or find records that match conditions across those tables.
  2. Step 2: Compare with includes

    includes is used to preload associated data to reduce queries, not for filtering.
  3. Final Answer:

    To combine tables and filter records based on matching columns -> Option C
  4. Quick Check:

    joins = combine tables for filtering [OK]
Hint: Remember: joins filters by matching tables, includes preloads data [OK]
Common Mistakes:
  • Confusing joins with includes
  • Thinking joins preload data
  • Assuming joins update or delete records
2. Which of the following is the correct syntax to use includes to preload the comments association on a Post model?
easy
A. Post.includes('comments').where(published: true)
B. Post.includes(:comments).where(published: true)
C. Post.include(:comments).where(published: true)
D. Post.joins(:comments).includes.where(published: true)

Solution

  1. Step 1: Check the correct method name and argument type

    The method is includes (plural), and it accepts a symbol like :comments.
  2. Step 2: Validate the chaining and syntax

    Post.includes(:comments).where(published: true) uses Post.includes(:comments).where(published: true), which is correct syntax to preload comments and filter posts.
  3. Final Answer:

    Post.includes(:comments).where(published: true) -> Option B
  4. Quick Check:

    Correct method and symbol argument = Post.includes(:comments).where(published: true) [OK]
Hint: Use plural includes with symbol for associations [OK]
Common Mistakes:
  • Using singular include instead of includes
  • Passing association as string instead of symbol
  • Chaining includes incorrectly
3. Given these models: Author has_many :books and Book belongs_to :author, what will this query return?
Author.joins(:books).where(books: { published: true }).distinct
medium
A. All authors with all their books loaded
B. All books that are published
C. All authors including those without books
D. All authors who have at least one published book

Solution

  1. Step 1: Analyze the joins and where clause

    The query joins authors with books and filters books where published: true.
  2. Step 2: Understand the effect of distinct

    distinct ensures authors are unique even if they have multiple published books.
  3. Final Answer:

    All authors who have at least one published book -> Option D
  4. Quick Check:

    joins + where filters authors by published books [OK]
Hint: joins filters parents by child conditions; distinct avoids duplicates [OK]
Common Mistakes:
  • Thinking it returns books instead of authors
  • Assuming includes loads all books
  • Ignoring distinct causing duplicates
4. Identify the error in this Rails query:
Post.joins(:comments).includes(:author).where(comments: { approved: true })
medium
A. No error; the query is valid and will work as expected
B. The where clause should reference authors instead of comments
C. Using both joins and includes together causes a syntax error
D. The includes should come before joins to avoid errors

Solution

  1. Step 1: Check if using joins and includes together is allowed

    Rails allows chaining joins and includes to combine filtering and eager loading.
  2. Step 2: Verify the where clause references a valid table

    The where filters on comments which is joined, so it's valid.
  3. Final Answer:

    No error; the query is valid and will work as expected -> Option A
  4. Quick Check:

    joins + includes + where on joined table = valid [OK]
Hint: joins and includes can be chained; where must match joined tables [OK]
Common Mistakes:
  • Thinking joins and includes can't be combined
  • Confusing which table to filter in where
  • Assuming order of joins/includes causes errors
5. You want to fetch all Order records with their associated Customer and OrderItems, but only include orders where the customer is active and at least one order item is in stock. Which query correctly uses joins and includes to achieve this efficiently?
hard
A. Order.joins(:customer, :order_items).includes(:customer, :order_items).where(customers: { active: true }, order_items: { in_stock: true }).distinct
B. Order.includes(:customer, :order_items).where(customers: { active: true }, order_items: { in_stock: true })
C. Order.joins(:customer).includes(:order_items).where(customers: { active: true }).where(order_items: { in_stock: true })
D. Order.joins(:customer).joins(:order_items).where(customers: { active: true }, order_items: { in_stock: true })

Solution

  1. Step 1: Understand filtering and eager loading needs

    We must filter orders by customer active status and order items in stock, so joins is needed to filter across tables.
  2. Step 2: Use includes to preload associations for efficient access

    To avoid N+1 queries when accessing customers and order items, includes preloads them.
  3. Step 3: Use distinct to avoid duplicate orders from multiple matching order items

    Because joins can cause duplicates, distinct ensures unique orders.
  4. Final Answer:

    Order.joins(:customer, :order_items).includes(:customer, :order_items).where(customers: { active: true }, order_items: { in_stock: true }).distinct -> Option A
  5. Quick Check:

    joins filters, includes preloads, distinct removes duplicates [OK]
Hint: Use joins to filter, includes to preload, distinct to avoid duplicates [OK]
Common Mistakes:
  • Using only includes without joins for filtering
  • Not using distinct causing duplicate records
  • Mixing joins and includes incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard