Skip to main content
April 1, 2026Noble Desktop Publishing Team/7 min read

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.

Topics Covered in This Ruby on Rails Tutorial:

Generating & Rolling Back a Migration, Updating Views & Controllers to Match an Updated Model

Exercise Preview

model management exercise preview

Exercise Overview

In this hands-on exercise, we'll demonstrate one of Rails' most powerful features: the ability to evolve your database schema safely and efficiently through migrations. You'll add additional columns to the movie model and learn how to synchronize views and controllers with these structural changes—a critical skill for maintaining production applications.

This exercise simulates a real-world scenario where business requirements change after initial development. Understanding how to manage these changes without breaking existing functionality is essential for any Rails developer working in a professional environment.

  1. If you completed the previous exercises, you can skip the following sidebar. We strongly recommend completing the previous exercises before starting this one, as they build the foundation for the concepts we'll explore here. If you haven't finished them, follow the setup instructions below.

    Prerequisites Required

    This exercise builds on previous Rails exercises 3A-4B. If you haven't completed them, follow the setup instructions to get the proper starting point from the Git repository.

If You Did Not Do the Previous Exercises (3A–4B)

  1. Close any files you may have open.
  2. Open the Finder and navigate to Class Files > yourname-Rails Class
  3. Open Terminal.
  4. Type cd and a single space (do NOT press Return yet).
  5. Drag the yourname-Rails Class folder from the Finder to the Terminal window and press ENTER.
  6. Run rm -rf flix to delete your copy of the Flix site.
  7. Run Git clone https://bitbucket.org/Noble Desktop/flix.Git to copy the Flix Git repository.
  8. Type cd flix to enter the new directory.
  9. Type Git checkout 4B to bring the site up to the end of the previous exercise.
  10. Run bundle to install any necessary gems.
  11. Run yarn install—check-files to install JavaScript dependencies.

Project Setup Recovery Process

1

Clean Existing Files

Remove any existing flix directory using rm -rf flix to start fresh

2

Clone Repository

Download the complete project using Git clone from the Noble Desktop repository

3

Restore State

Use Git checkout 4B to jump to the exact point where the previous exercises ended

4

Install Dependencies

Run bundle and yarn install to ensure all gems and JavaScript packages are properly installed

Getting Started

Let's set up your development environment to begin working with database migrations. Proper workspace organization is crucial when working with Rails applications, especially when dealing with database changes that could affect your entire application.

  1. Close all of the files you have open in your code editor.

  2. Open the Finder and navigate to Class Files > yourname-Rails Class

  3. Open Terminal.

  4. Type cd and a single space (do NOT press Return yet).

  5. Drag the flix folder from the Finder to the Terminal window.

  6. Make sure you're in Terminal and hit Return to change into the new folder.

Terminal Navigation Tip

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.

Generating & Rolling Back a Migration

Here's where Rails truly shines in enterprise development. The movie model we created in previous exercises isn't set in stone—one of Rails' greatest strengths is its ability to evolve database schemas safely over time. In real-world applications, requirements change constantly, and Rails migrations provide a robust, version-controlled way to implement these changes without losing data or breaking existing functionality.

Imagine you're working at a streaming company, and the Editorial Department at Flix has requested a new director field for the Movie Details sidebar on each detail page. This scenario happens daily in professional development environments, and handling it gracefully separates experienced developers from novices.

Since we already have an established model, we won't use rails generate model again. Instead, we'll use rails generate migration—a more surgical approach that modifies existing database structures while preserving data integrity.

  1. Type the following command, but do NOT press Return yet:

    rails generate migration

    Migrations are the backbone of Rails' database management system. They allow you to modify your database schema in a controlled, reversible way—crucial for team environments where multiple developers need to synchronize database changes.

  2. Complete the command with a descriptive name and field specification, then press Return:

    rails generate migration add_director_to_movies director:text

    Terminal will confirm that a new migration file has been created. Notice how the naming convention add_X_to_Y helps Rails automatically understand your intent—this is Rails' "convention over configuration" philosophy in action.

  3. Switch to your code editor.

  4. Open flix > db > migrate > #_add_director_to_movies.rb (the # represents the file's unique timestamp).

  5. Examine this generated code:

    def change
       add_column :movies, :director, :text
    end

    Rails' intelligence shines here. By parsing our migration name add_director_to_movies, it automatically recognized that we want to modify the existing movies table and generated the appropriate add_column command. This convention-based approach reduces boilerplate code and minimizes errors.

  6. Let's apply this migration. Switch to Terminal.

  7. Run the migration:

    rails db:migrate

    Terminal should confirm with an add_column message—but wait! We've made a design error. The director field should be a simple string, not a text area. In a production environment, this kind of mistake could impact user experience and data validation. Fortunately, Rails provides an elegant solution: migration rollbacks.

  8. Roll back the migration:

    rails db:rollback

    Notice how Terminal reports it's reverting with a remove_column action—the exact opposite of our original add_column. This reversibility is what makes Rails migrations so powerful in team environments and production deployments.

  9. Now let's correct our migration file. Switch to #_add_director_to_movies.rb in your code editor.

  10. Make this crucial correction, changing text to string:

    def change
       add_column :movies, :director, :string
    end

    This change ensures our director field will be rendered as a standard text input rather than a textarea, providing a better user experience for single-line data entry.

  11. Save the file.

  12. Switch to Terminal.

  13. Apply the corrected migration:

    rails db:migrate

    Perfect! The corrected migration is now applied. This rollback-and-fix workflow is standard practice in professional Rails development, allowing teams to iterate quickly while maintaining database integrity.

Migration Generation vs Model Generation

Featurerails generate migrationrails generate model
PurposeModify existing modelsCreate new models
Database ImpactAdds/modifies columnsCreates new tables
When to UseModel already existsCreating new model
File GenerationMigration file onlyModel, migration, tests
Recommended: Use migrations for existing models, generate model for new entities
Smart Migration Naming

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

1

Identify the Error

Recognize that director should be string type, not text type for the database field

2

Rollback Migration

Use rails db:rollback to undo the migration and revert database changes

3

Edit Migration File

Change the field type from :text to :string in the migration file

4

Reapply Migration

Run rails db:migrate again to apply the corrected migration

Migration Safety

Always rollback and fix migrations rather than editing applied migrations. This maintains database integrity and ensures consistent deployment across environments.

Updating Views & Controllers to Match an Updated Model

Adding database columns is only the first step. To complete the feature implementation, we need to update the application's views and controllers—a process that demonstrates Rails' MVC architecture in action. This synchronization between model, view, and controller is critical for maintaining data flow throughout your application.

  1. Switch to your code editor.

  2. Open flix > app > views > movies > _form.html.erb

  3. Add the director input field after the has_subtitles section (around line 14):

    <%= f.label :has_subtitles %>
       <%= f.check_box :has_subtitles %>
    </p>
    <p>
       <%= f.label :director %>
       <%= f.text_field :director %>
    </p>

    This Rails form helper automatically generates the appropriate HTML input with proper naming conventions for Rails' parameter handling.

  4. Save the file.

  5. Open flix > app > controllers > movies_controller.rb

  6. Navigate to the bottom of the file and locate the private movie_params method. This method implements Rails' strong parameters feature—a security measure that prevents mass assignment vulnerabilities. Add :director to the permitted parameters:

    movie_params = params.require(:movie).permit(:title, :description, :has_subtitles, :placement, :mpaa_rating, :release_date, :ticket_price, :runtime, :poster_image, :director)

    Critical Note: Forgetting to update movie_params is one of the most common mistakes when adding new fields. Without this change, Rails will silently ignore the new field data for security reasons, leading to frustrating debugging sessions. Always remember: new model field → update strong parameters.

  7. Save the file.

    Now let's ensure the director information displays properly in the movie details view.

  8. Open flix > app > views > movies > show.html.erb

  9. Around line 15, add the container div for the director information:

    <div class="details">
       <h4>Movie Details</h4>
       <div>
          <span></span>
       </div><div>
          <span>Subtitles:</span>
  10. Complete the director display section:

    <div class="details">
       <h4>Movie Details</h4>
       <div>
          <span>Director:</span>
          <%= @movie.director %>
       </div>
       <div>
          <span>Subtitles:</span>

    The <%= @movie.director %> erb tag will output the director's name, with Rails automatically handling nil values gracefully.

  11. Save the file.

  12. Launch the Rails development server:

    rails server
  13. Open your browser and navigate to localhost:3000/movies/1/edit to see the new director field in action.

  14. Test the functionality by entering a director name:

    Director: Sam Badams
  15. Click Update Movie to save your changes.

    The director information should now appear in the Movie Details sidebar, demonstrating the complete data flow from form input through controller processing to database storage and view display. This end-to-end functionality showcases Rails' elegant MVC implementation.

You've successfully implemented a complete feature addition workflow: generating and refining a migration, updating the form interface, configuring controller security parameters, and displaying the new data in views. This process mirrors the daily reality of professional Rails development, where evolving requirements demand both technical skill and systematic thinking.

Complete Model Update Checklist

0/4
Common Oversight

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

1Use rails generate migration to modify existing models rather than generating new models
2Rails automatically parses migration names like 'add_field_to_table' to determine the target table and operation
3Always rollback incorrect migrations using rails db:rollback instead of editing applied migrations
4Strong parameters in controllers must be updated when adding new model fields to forms
5Model changes require updates in three locations: migration file, view templates, and controller parameters
6Migration rollbacks perform the inverse operation automatically, like remove_column for add_column
7Field types matter in migrations - choose string for short text and text for longer content
8The MVC pattern requires synchronized updates across all three components when modifying data models

RELATED ARTICLES