Link Expenses to Users
Exit
Link Expenses to Users
Add a user_id field to the Expense model
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Every expense needs an owner
Right now, expenses have no connection to the user who created them. Once you protect the endpoints, you need a way to record which user owns each expense. A user_id field solves this.
The field is a plain int that stores the user's identifier. Conceptually, it references the id column in the User table. You keep it simple here — no foreign key constraint, just a plain integer field. The application logic ensures that user_id always matches a real user.
Instructions
Add a user_id field to the Expense model.
- Add
user_id: intas a new field in theExpenseclass, after thedatefield. Every expense will store the identifier of the user who created it, so you can filter and enforce ownership later.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding