Bird
Raised Fist0
Ruby on Railsframework~20 mins

Many-to-many with has_many through in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Master of Many-to-many Associations
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
Understanding the association output
Given the following Rails models, what will user.posts return after creating the associations?

class User < ApplicationRecord
  has_many :user_posts
  has_many :posts, through: :user_posts
end

class Post < ApplicationRecord
  has_many :user_posts
  has_many :users, through: :user_posts
end

class UserPost < ApplicationRecord
  belongs_to :user
  belongs_to :post
end

# Setup
user = User.create(name: 'Alice')
post1 = Post.create(title: 'Hello')
post2 = Post.create(title: 'World')
UserPost.create(user: user, post: post1)
UserPost.create(user: user, post: post2)
AAn array containing only post1 object
BAn empty array
CAn array containing only post2 object
DAn array containing post1 and post2 objects
Attempts:
2 left
💡 Hint
Think about how has_many through works to connect user and posts via user_posts.
📝 Syntax
intermediate
2:00remaining
Correct syntax for has_many through association
Which of the following is the correct way to declare a many-to-many association between Author and Book using a join model Authorship in Rails?
A
class Author &lt; ApplicationRecord
  has_many :books
  has_many :authorships, through: :books
end
B
class Author &lt; ApplicationRecord
  has_many :authorships
  has_many :books, through: :authorships
end
C
class Author &lt; ApplicationRecord
  has_many :authorships, through: :books
  has_many :books
end
D
class Author &lt; ApplicationRecord
  has_many :books, through: :authorships
end
Attempts:
2 left
💡 Hint
Remember the join model should be declared first, then the through association.
🔧 Debug
advanced
2:00remaining
Why does user.posts return empty?
Given these models:

class User < ApplicationRecord
  has_many :user_posts
  has_many :posts, through: :user_posts
end

class Post < ApplicationRecord
  has_many :user_posts
  has_many :users, through: :user_posts
end

class UserPost < ApplicationRecord
  belongs_to :user
  belongs_to :post
end

# Data
user = User.create(name: 'Bob')
post = Post.create(title: 'Rails Tips')
# Missing association creation here

puts user.posts.inspect

Why does user.posts return an empty array?
ABecause no UserPost record links the user and post
BBecause the has_many :posts association is missing
CBecause the User model should use has_and_belongs_to_many instead
DBecause the Post model lacks a belongs_to :user
Attempts:
2 left
💡 Hint
Check if the join table has any records connecting user and post.
❓ state_output
advanced
2:00remaining
Effect of destroying a join record
If a UserPost record linking a user and a post is destroyed, what happens to user.posts?
Auser.posts still includes the post because the association caches it
BThe post record is deleted from the database
CThe post is removed from user.posts but the post record remains in the database
DAn error is raised when accessing user.posts
Attempts:
2 left
💡 Hint
Think about what destroying a join record affects in a many-to-many association.
🧠 Conceptual
expert
2:00remaining
Why use has_many through instead of has_and_belongs_to_many?
Which is the main advantage of using has_many :through over has_and_belongs_to_many in Rails many-to-many associations?
Ahas_many through allows adding extra attributes to the join model
Bhas_and_belongs_to_many supports validations on the join table
Chas_many through automatically creates the join table without migration
Dhas_and_belongs_to_many is deprecated and no longer works
Attempts:
2 left
💡 Hint
Think about what you can do with the join model in has_many through.

Practice

(1/5)
1. What is the main purpose of using has_many :through in Rails models?
easy
A. To create a many-to-many relationship using a join model
B. To create a one-to-one relationship between two models
C. To validate data before saving to the database
D. To automatically generate database migrations

Solution

  1. Step 1: Understand relationship types in Rails

    Rails uses associations to connect models. has_many :through is specifically for many-to-many relationships.
  2. Step 2: Identify the role of join models

    It uses a join model to connect two other models, allowing extra data on the connection.
  3. Final Answer:

    To create a many-to-many relationship using a join model -> Option A
  4. Quick Check:

    has_many :through = many-to-many with join model [OK]
Hint: Think: many-to-many needs a join model [OK]
Common Mistakes:
  • Confusing has_many :through with has_one
  • Thinking it automatically creates migrations
  • Using it for one-to-one relationships
2. Which of the following is the correct way to declare a many-to-many association using has_many :through in the Author model?
easy
A. has_one :books, through: :authorships
B. has_many :books, through: :authorships
C. belongs_to :books, through: :authorships
D. has_many :authorships, through: :books

Solution

  1. Step 1: Identify the correct association syntax

    The model that wants to access the other through a join model uses has_many :other_model, through: :join_model.
  2. Step 2: Apply to Author model

    Author has many books through authorships, so has_many :books, through: :authorships is correct.
  3. Final Answer:

    has_many :books, through: :authorships -> Option B
  4. Quick Check:

    has_many :books, through: :authorships = correct syntax [OK]
Hint: Remember: has_many :target, through: :join_model [OK]
Common Mistakes:
  • Reversing the join and target models
  • Using belongs_to instead of has_many
  • Using has_one for many-to-many
3. Given these models:
class Author < ApplicationRecord
  has_many :authorships
  has_many :books, through: :authorships
end

class Authorship < ApplicationRecord
  belongs_to :author
  belongs_to :book
end

class Book < ApplicationRecord
  has_many :authorships
  has_many :authors, through: :authorships
end

What will Author.first.books.count return if the first author has 3 books linked through authorships?
medium
A. 1
B. 0
C. 3
D. An error because of missing join table

Solution

  1. Step 1: Understand the association setup

    Author has many books through authorships, so calling Author.first.books fetches all books linked via authorships.
  2. Step 2: Count the linked books

    If the first author has 3 books linked, Author.first.books.count returns 3.
  3. Final Answer:

    3 -> Option C
  4. Quick Check:

    Author.first.books.count = number of linked books [OK]
Hint: Count returns linked records through join model [OK]
Common Mistakes:
  • Assuming count returns authorships count
  • Expecting zero without checking data
  • Confusing belongs_to with has_many effects
4. You have these models:
class Student < ApplicationRecord
  has_many :enrollments
end

class Enrollment < ApplicationRecord
  belongs_to :student
  belongs_to :course
end

class Course < ApplicationRecord
  has_many :enrollments
  has_many :students, through: :enrollments
end

But when you run Student.first.courses, you get an error: undefined method 'courses'. What is the likely cause?
medium
A. The has_many :courses, through: :enrollments line is missing in Student model
B. The Enrollment model is missing belongs_to :course
C. The Course model should use belongs_to :student instead of has_many
D. The database table for enrollments does not exist

Solution

  1. Step 1: Check Student model associations

    The error says courses method is undefined, meaning Student model lacks has_many :courses, through: :enrollments.
  2. Step 2: Confirm other associations

    Enrollment and Course models are correct; missing association in Student causes the error.
  3. Final Answer:

    The has_many :courses, through: :enrollments line is missing in Student model -> Option A
  4. Quick Check:

    Missing has_many through causes undefined method [OK]
Hint: Check if has_many :through is declared in the model [OK]
Common Mistakes:
  • Assuming belongs_to missing causes undefined method
  • Thinking Course model needs belongs_to Student
  • Ignoring missing database tables as cause
5. You want to track the date when a User joins a Group using a many-to-many relationship with has_many :through. Which setup correctly allows storing this extra data?
hard
A. Add joined_on column directly to users table and use has_many :groups
B. Store joined_on in a separate table unrelated to the join
C. Use has_and_belongs_to_many :groups without a join model
D. Create a join model Membership with user_id, group_id, and joined_on columns, then use has_many :groups, through: :memberships in User

Solution

  1. Step 1: Understand storing extra data in many-to-many

    Extra data on the connection requires a join model with its own columns.
  2. Step 2: Apply to User and Group

    Create a join model Membership with user_id, group_id, and joined_on columns. Then User uses has_many :groups, through: :memberships.
  3. Final Answer:

    Create a join model Membership with user_id, group_id, and joined_on columns, then use has_many :groups, through: :memberships in User -> Option D
  4. Quick Check:

    Extra data needs join model with columns [OK]
Hint: Use join model to store extra data in many-to-many [OK]
Common Mistakes:
  • Adding extra columns to main models instead of join model
  • Using has_and_belongs_to_many which lacks extra data support
  • Storing extra data in unrelated tables
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