A. Missing value for name in the last User.create call
B. User.create cannot be called multiple times
C. Names must be unique, so this will fail
D. The code should be inside a loop
Solution
Step 1: Check syntax of each User.create call
The first two calls have valid name values. The last call has name: with no value, which is a syntax error.
Step 2: Verify other options
Calling User.create multiple times is allowed. Names do not have to be unique unless validated. Loop is optional.
Final Answer:
Missing value for name in the last User.create call -> Option A
Quick Check:
Empty value after name: causes syntax error [OK]
Hint: Check for missing values after keys in hashes [OK]
Common Mistakes:
Thinking multiple create calls are invalid
Assuming uniqueness is required by default
Believing loops are mandatory for seeds
5. You want to seed your database with categories but only if they don't already exist. Which seed code snippet correctly does this?
hard
A. ['Books', 'Movies', 'Music'].each do |name|
Category.find_or_create_by(name: name)
end
B. ['Books', 'Movies', 'Music'].each do |name|
Category.create(name: name)
end
C. Category.delete_all
['Books', 'Movies', 'Music'].each do |name|
Category.create(name: name)
end
D. Category.create(['Books', 'Movies', 'Music'])
Solution
Step 1: Understand the requirement to avoid duplicates
We want to add categories only if they don't exist yet, so we must check before creating.
Step 2: Analyze each option
['Books', 'Movies', 'Music'].each do |name|
Category.create(name: name)
end always creates new records, causing duplicates. ['Books', 'Movies', 'Music'].each do |name|
Category.find_or_create_by(name: name)
end uses find_or_create_by which checks existence before creating. Category.delete_all
['Books', 'Movies', 'Music'].each do |name|
Category.create(name: name)
end deletes all categories first, which is destructive. Category.create(['Books', 'Movies', 'Music']) tries to create with an array directly, which is invalid syntax.
Final Answer:
['Books', 'Movies', 'Music'].each do |name|
Category.find_or_create_by(name: name)
end -> Option A
Quick Check:
Use find_or_create_by to avoid duplicates [OK]
Hint: Use find_or_create_by to prevent duplicate seed entries [OK]
Common Mistakes:
Creating records without checking duplicates
Deleting all data before seeding unnecessarily
Passing array directly to create without hashes
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.