0
0
Ruby on Railsframework~20 mins

Active Record pattern in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Active Record Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Active Record query?
Given a Rails model 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?
A['Rails Advanced', 'JavaScript Guide']
B['Ruby Basics', 'Rails Advanced']
C['Ruby Basics', 'JavaScript Guide']
D['Rails Advanced']
Attempts:
2 left
💡 Hint
Think about which books have more than 180 pages.
lifecycle
intermediate
1: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?
Aafter_create
Bbefore_create
Cbefore_save
Dafter_save
Attempts:
2 left
💡 Hint
It runs before both creating and updating the record.
📝 Syntax
advanced
2:00remaining
What error does this Active Record code raise?
Consider this code snippet:

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?
AActiveRecord::StatementInvalid
BActiveRecord::RecordNotFound
CActiveRecord::RecordInvalid
DNo error, update succeeds
Attempts:
2 left
💡 Hint
Think about what happens when the database rejects a null value for a NOT NULL column.
state_output
advanced
1:30remaining
What is the value of user.persisted? after user.destroy?
Given:

user = User.create(name: 'Alice')
user.destroy


What does user.persisted? return after the destroy call?
Atrue
Bfalse
Cnil
DRaises an error
Attempts:
2 left
💡 Hint
Think about whether the object still exists in the database after destroy.
🔧 Debug
expert
2:30remaining
Why does this Active Record query raise an error?
Examine this code:

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?
ANo error, returns the order with ID 1
BActiveRecord::StatementInvalid due to invalid SQL syntax
CActiveRecord::RecordInvalid because status is invalid
DActiveRecord::RecordNotFound because the order with ID 1 does not match the status condition
Attempts:
2 left
💡 Hint
Remember that find respects scopes and where filters the query.