Model Creation & Management
Master Rails Model Management and Database Migrations
Core Rails Model Management Skills
Migration Generation
Create and modify database schema changes using Rails generators. Learn to add, modify, and remove columns from existing models safely.
Rollback Recovery
Handle migration errors gracefully by rolling back changes and fixing issues. Never lose data due to migration mistakes.
MVC Synchronization
Keep models, views, and controllers in sync when making schema changes. Update all components to reflect new data fields.
Project Setup Recovery Process
Clean Existing Files
Remove any existing flix directory using rm -rf flix to start fresh
Clone Repository
Download the complete project using Git clone from the Noble Desktop repository
Restore State
Use Git checkout 4B to jump to the exact point where the previous exercises ended
Install Dependencies
Run bundle and yarn install to ensure all gems and JavaScript packages are properly installed
Use drag-and-drop from Finder to Terminal for accurate path entry. Type 'cd ' (with space), drag the folder, then press Return to navigate efficiently.
Migration Generation vs Model Generation
| Feature | rails generate migration | rails generate model |
|---|---|---|
| Purpose | Modify existing models | Create new models |
| Database Impact | Adds/modifies columns | Creates new tables |
| When to Use | Model already exists | Creating new model |
| File Generation | Migration file only | Model, migration, tests |
Rails automatically parses migration names like 'add_director_to_movies' to understand which table to modify and what operation to perform. This convention saves significant development time.
Migration Rollback and Fix Process
Identify the Error
Recognize that director should be string type, not text type for the database field
Rollback Migration
Use rails db:rollback to undo the migration and revert database changes
Edit Migration File
Change the field type from :text to :string in the migration file
Reapply Migration
Run rails db:migrate again to apply the corrected migration
Always rollback and fix migrations rather than editing applied migrations. This maintains database integrity and ensures consistent deployment across environments.
Complete Model Update Checklist
Add form elements in _form.html.erb for user input
Add new field to strong parameters in movie_params method
Show new field data in show.html.erb template
Verify field saves and displays correctly in browser
Forgetting to add new fields to the strong parameters in the controller will cause form submissions to silently fail. The field won't save even though everything else appears to work correctly.
Key Takeaways
