0
0
Ruby on Railsframework~20 mins

CRUD operations through models in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rails Model Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2: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
A"Alice"
Bnil
C""
DRaises ActiveRecord::RecordInvalid error
Attempts:
2 left
💡 Hint
The create method saves the record and returns the object with attributes set.
state_output
intermediate
2: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?
Afalse
Btrue
Cnil
DRaises NoMethodError
Attempts:
2 left
💡 Hint
The save method returns true if the record was saved successfully.
🔧 Debug
advanced
2: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)
AValidation fails because name cannot be nil, so update returns false and does not raise error
Bupdate raises ActiveRecord::RecordInvalid because validations fail and update! was called
Cupdate raises NoMethodError because name is nil
Dupdate raises ActiveRecord::RecordNotFound because user id 1 does not exist
Attempts:
2 left
💡 Hint
Check if update or update! is used and how validations behave.
📝 Syntax
advanced
2: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?
AUser.delete(5)
BUser.remove(5)
CUser.destroy(5)
DUser.destroy_by(id: 5)
Attempts:
2 left
💡 Hint
Consider which methods trigger callbacks and which do not.
🧠 Conceptual
expert
2: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
Anil
B"Carol"
CRaises ActiveRecord::RecordNotFound
D"Diana"
Attempts:
2 left
💡 Hint
The reload method refreshes the object from the database.