Challenge - 5 Problems
Rails Associations Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate2:00remaining
Why use associations between models in Rails?
What is the main reason Rails uses associations to connect models?
Attempts:
2 left
💡 Hint
Think about how Rails helps you get related records.
✗ Incorrect
Associations in Rails link models so you can fetch related data simply, avoiding manual SQL joins.
❓ component_behavior
intermediate2:00remaining
What happens when you call
has_many in a model?In Rails, what does adding
has_many :comments inside a Post model do?Attempts:
2 left
💡 Hint
Think about what
has_many means in terms of data access.✗ Incorrect
The has_many association adds a method to get all related comments for a post.
❓ state_output
advanced2:00remaining
Output of accessing associated records
Given these models:
What is the output?
class Author < ApplicationRecord has_many :books end class Book < ApplicationRecord belongs_to :author end author = Author.create(name: 'Jane') author.books.create(title: 'Book 1') author.books.create(title: 'Book 2') puts author.books.count
What is the output?
Attempts:
2 left
💡 Hint
How many books did we add to the author?
✗ Incorrect
Two books were created for the author, so author.books.count returns 2.
📝 Syntax
advanced2:00remaining
Identify the correct association syntax
Which option correctly sets up a one-to-one association where a User has one Profile?
Attempts:
2 left
💡 Hint
Remember singular vs plural and which side owns the foreign key.
✗ Incorrect
Option A correctly uses has_one and belongs_to with singular names.
🔧 Debug
expert3:00remaining
Why does accessing an association raise an error?
Given these models:
Why does this code raise an error?
class Order < ApplicationRecord has_many :items end class Item < ApplicationRecord belongs_to :order end order = Order.new order.items.first.name
Why does this code raise an error?
Attempts:
2 left
💡 Hint
What happens when you call a method on nil?
✗ Incorrect
Since order is not saved, it has no items. Calling first returns nil, then name on nil raises NoMethodError.