💎 Ruby on Rails
Beginner
What is the difference between find and find_by in Rails?
Answer
User.find(id) looks up a record by primary key and raises ActiveRecord::RecordNotFound if not found. This is used when the record must exist — letting the exception propagate results in a 404 response with proper rescue handling. User.find_by(email: 'a@b.com') searches by any attribute and returns nil if not found — useful when absence is a normal case (e.g., checking login credentials). find_by! raises RecordNotFound like find. Choosing between them communicates intent about whether a missing record is expected.