Challenge - 5 Problems
Rails Model Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What does this Rails model code output after creation?
Consider the following Rails model code snippet. What will be the value of
user.name after running this code?Ruby on Rails
user = User.create(name: "Alice", age: 30) user.name
Attempts:
2 left
💡 Hint
The
create method saves the record and returns the object with attributes set.✗ Incorrect
The create method in Rails creates and saves a new record. The returned object has the attributes assigned, so user.name will be "Alice".
❓ state_output
intermediate2:00remaining
What is the value of
user.persisted? after new and save?Given the following code, what will
user.persisted? return after the save call?Ruby on Rails
user = User.new(name: "Bob")
saved = user.save
user.persisted?Attempts:
2 left
💡 Hint
The
save method returns true if the record was saved successfully.✗ Incorrect
After calling save on a new record, if it succeeds, the record is persisted in the database. Thus, user.persisted? returns true.
🔧 Debug
advanced2:00remaining
Why does this update raise an error?
Examine the code below. Why does
user.update(name: nil) raise an error if the model validates presence of name?Ruby on Rails
user = User.find(1)
user.update(name: nil)Attempts:
2 left
💡 Hint
Check if
update or update! is used and how validations behave.✗ Incorrect
The update method returns false if validations fail but does not raise an error. Only update! raises an exception on validation failure.
📝 Syntax
advanced2:00remaining
Which option correctly deletes a record by id?
Which of the following Rails model commands correctly deletes the user with id 5 from the database?
Attempts:
2 left
💡 Hint
Consider which methods trigger callbacks and which do not.
✗ Incorrect
destroy deletes the record and runs callbacks. delete deletes without callbacks. remove is not a valid method. destroy_by deletes by conditions but returns the number of records deleted.
🧠 Conceptual
expert2:00remaining
What is the result of chaining
update and reload?Given this code, what will
user.name be after the last line?Ruby on Rails
user = User.create(name: "Carol") user.update(name: "Diana") user.reload user.name
Attempts:
2 left
💡 Hint
The
reload method refreshes the object from the database.✗ Incorrect
The update changes the name to "Diana" in the database. reload refreshes the object with the latest data, so user.name is "Diana".