Challenge - 5 Problems
HasMany Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediateWhat does this Rails code output when accessing associated records?
Given the following models, what will
user.posts.count return after running the code below?Ruby on Rails
class User < ApplicationRecord has_many :posts end class Post < ApplicationRecord belongs_to :user end user = User.create(name: "Alice") user.posts.create(title: "First Post") user.posts.create(title: "Second Post") result = user.posts.count
Attempts:
2 left
💡 Hint
Remember that
has_many sets up a collection of associated records.✗ Incorrect
The user has two posts created and saved. Calling
user.posts.count returns the number of associated posts, which is 2.📝 Syntax
intermediateWhich option correctly defines a has_many association in Rails?
Select the correct syntax to define a
has_many association from User to Post.Attempts:
2 left
💡 Hint
The association name should be a symbol and plural for has_many.
✗ Incorrect
Option D uses the correct syntax:
has_many :posts. Option D misses the colon, C uses singular, and D uses quotes instead of a symbol.🔧 Debug
advancedWhy does this has_many association not load related records?
Given these models, why does
user.posts return an empty array even though posts exist in the database?Ruby on Rails
class User < ApplicationRecord has_many :posts end class Post < ApplicationRecord belongs_to :author end user = User.first posts = user.posts
Attempts:
2 left
💡 Hint
Check if the foreign key and association names match between models.
✗ Incorrect
The User model expects posts to belong to :user, but Post belongs_to :author, so Rails cannot link them. The association names must match for has_many and belongs_to.
❓ state_output
advancedWhat is the value of
post.user.name after this code runs?Consider these models and code. What will
post.user.name output?Ruby on Rails
class User < ApplicationRecord has_many :posts end class Post < ApplicationRecord belongs_to :user end user = User.create(name: "Bob") post = Post.create(title: "Hello", user: user) result = post.user.name
Attempts:
2 left
💡 Hint
The post belongs to the user created with name "Bob".
✗ Incorrect
The post is linked to the user with name "Bob". Accessing
post.user.name returns "Bob".🧠 Conceptual
expertWhich statement about has_many associations is true?
Select the correct statement about Rails
has_many associations.Attempts:
2 left
💡 Hint
Think about how Rails links models in a has_many relationship.
✗ Incorrect
has_many requires the associated model's table to have a foreign key column pointing back to the owner model. Other options are false: indexes are not automatic, belongs_to is recommended but not strictly required, and dependent option is supported.
