Challenge - 5 Problems
Active Record Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output of this Active Record query?
Given a Rails model
What does
Book with records:Book.create(title: 'Ruby Basics', pages: 150)
Book.create(title: 'Rails Advanced', pages: 300)
Book.create(title: 'JavaScript Guide', pages: 200)What does
Book.where('pages > ?', 180).pluck(:title) return?Attempts:
2 left
💡 Hint
Think about which books have more than 180 pages.
✗ Incorrect
The query filters books with pages greater than 180, which are 'Rails Advanced' (300 pages) and 'JavaScript Guide' (200 pages). The
pluck(:title) returns their titles as an array.❓ lifecycle
intermediate1:30remaining
Which callback runs before saving a record?
In Rails Active Record, which callback method is called before a record is saved to the database?
Attempts:
2 left
💡 Hint
It runs before both creating and updating the record.
✗ Incorrect
The
before_save callback runs before both creating a new record and updating an existing one. before_create runs only before creating a new record.📝 Syntax
advanced2:00remaining
What error does this Active Record code raise?
Consider this code snippet:
Assuming the
user = User.find_by(email: 'test@example.com')
user.update!(name: nil)Assuming the
name field has a NOT NULL database constraint, what error will this code raise?Attempts:
2 left
💡 Hint
Think about what happens when the database rejects a null value for a NOT NULL column.
✗ Incorrect
The
update! method raises an exception if the database rejects the update. Since name cannot be null, the database raises an error, which Active Record wraps as ActiveRecord::StatementInvalid.❓ state_output
advanced1:30remaining
What is the value of
user.persisted? after user.destroy?Given:
What does
user = User.create(name: 'Alice')
user.destroyWhat does
user.persisted? return after the destroy call?Attempts:
2 left
💡 Hint
Think about whether the object still exists in the database after destroy.
✗ Incorrect
After calling
destroy, the record is removed from the database, so persisted? returns false indicating it is no longer saved.🔧 Debug
expert2:30remaining
Why does this Active Record query raise an error?
Examine this code:
Assuming there is an order with ID 1 but its status is 'completed', why does this code raise an error?
Order.where(status: 'pending').find(1)Assuming there is an order with ID 1 but its status is 'completed', why does this code raise an error?
Attempts:
2 left
💡 Hint
Remember that
find respects scopes and where filters the query.✗ Incorrect
The
where scopes the query to only orders with status 'pending'. The find(1) looks for ID 1 within that scope. Since order 1 has status 'completed', it is not found, raising ActiveRecord::RecordNotFound.