Bird
Raised Fist0
Ruby on Railsframework~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of the Active Record pattern in Rails?
easy
A. To link Ruby classes with database tables for easy data management
B. To create user interfaces with Ruby code
C. To handle HTTP requests and responses
D. To style web pages using CSS

Solution

  1. Step 1: Understand Active Record's role

    Active Record connects Ruby classes to database tables, making data handling easier.
  2. Step 2: Compare options to this role

    Only To link Ruby classes with database tables for easy data management describes this connection; others describe unrelated tasks.
  3. Final Answer:

    To link Ruby classes with database tables for easy data management -> Option A
  4. Quick Check:

    Active Record = Ruby class to DB table link [OK]
Hint: Active Record links Ruby classes to tables [OK]
Common Mistakes:
  • Confusing Active Record with view or controller roles
  • Thinking it handles HTTP or styling
  • Assuming it writes SQL directly
2. Which of the following is the correct way to find a record by its ID using Active Record?
easy
A. User.find_by_id(5)
B. User.where(id: 5).first!
C. User.find(5)
D. User.get(5)

Solution

  1. Step 1: Recall Active Record find methods

    The method find fetches a record by its ID directly.
  2. Step 2: Check each option

    User.find(5) uses find(5), which is correct. User.find_by_id(5) is deprecated. User.where(id: 5).first! is valid but less direct. User.get(5) is invalid.
  3. Final Answer:

    User.find(5) -> Option C
  4. Quick Check:

    Use find(id) to get record by ID [OK]
Hint: Use find(id) to get record by ID [OK]
Common Mistakes:
  • Using deprecated find_by_id instead of find
  • Using invalid method names like get
  • Confusing where.first! with find for simple ID lookup
3. Given the code:
user = User.find(3)
user.update(name: "Alice")
puts user.name

What will be printed?
medium
A. Alice
B. An error message
C. nil
D. 3

Solution

  1. Step 1: Understand the update method

    The update method changes the record's attributes and saves it.
  2. Step 2: Check the output of puts user.name

    After updating, user.name is "Alice", so it prints "Alice".
  3. Final Answer:

    Alice -> Option A
  4. Quick Check:

    update changes attribute, then prints new value [OK]
Hint: update changes and saves record attributes [OK]
Common Mistakes:
  • Thinking update returns the ID
  • Assuming update does not save changes
  • Expecting nil or error without reason
4. What is wrong with this code snippet?
post = Post.find(10)
post.title = "New Title"
post.save!
medium
A. Using save! will not save changes
B. No error; this code correctly updates the post title
C. Assigning title directly is not allowed
D. find(10) returns an array, not a single record

Solution

  1. Step 1: Analyze the code actions

    The code finds a post by ID, changes its title, then saves it with save!.
  2. Step 2: Check if any step is invalid

    Assigning attributes directly and using save! is valid and will update the record.
  3. Final Answer:

    No error; this code correctly updates the post title -> Option B
  4. Quick Check:

    Direct attribute assignment + save! updates record [OK]
Hint: Direct attribute change + save! updates record [OK]
Common Mistakes:
  • Thinking save! does not save changes
  • Believing find returns an array
  • Assuming direct assignment is forbidden
5. You want to get all users who signed up after January 1, 2023, and order them by their signup date descending. Which Active Record query is correct?
hard
A. User.select_all.where(created_at > '2023-01-01').order_desc('created_at')
B. User.find_by(created_at: '> 2023-01-01').sort(created_at: :desc)
C. User.filter(created_at > '2023-01-01').order_by('created_at desc')
D. User.where('created_at > ?', '2023-01-01').order(created_at: :desc)

Solution

  1. Step 1: Identify correct where syntax

    Active Record uses where('created_at > ?', date) to filter by date.
  2. Step 2: Identify correct order syntax

    Ordering is done with order(created_at: :desc) for descending order.
  3. Step 3: Compare options

    Only User.where('created_at > ?', '2023-01-01').order(created_at: :desc) uses correct where and order syntax; others use invalid or non-existent methods.
  4. Final Answer:

    User.where('created_at > ?', '2023-01-01').order(created_at: :desc) -> Option D
  5. Quick Check:

    where + order with symbols = correct query [OK]
Hint: Use where with ? and order with symbol for sorting [OK]
Common Mistakes:
  • Using find_by instead of where for multiple records
  • Using non-existent methods like filter or order_desc
  • Incorrect syntax in where clause
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard