DEV Community

Maya Sheriff
Maya Sheriff

Posted on

Rails Migration Tips and Examples (not a full step by step)

Generates the model and migration, but also all of the RCAVs for index, show, create, update, and destroy.

  • The model name must be singular.
  • Separate column names and datatypes with colons (NO SPACES).
  • Separate name:datatype pairs with spaces (NO COMMAS).
rails generate draft:resource <MODEL_NAME_SINGULAR> <COLUMN_1_NAME>:<COLUMN_1_DATATYPE> <COLUMN_2_NAME>:<COLUMN_2_DATATYPE> # etc

EX:
rails generate draft:resource board name:string
        OR
rails generate draft:resource post title:string body:text expires_on:date board_id:integer
Enter fullscreen mode Exit fullscreen mode

Execute the generated migrations with:

rake db:migrate
Enter fullscreen mode Exit fullscreen mode

This will remove all the files that rails generate draft:resource post ... had previously added. You can then correct your error and re-generate from scratch.

rails destroy draft:resource post
Enter fullscreen mode Exit fullscreen mode

If you made a mistake when generating your draft:resource AND you’ve already run rake db:migrate, then first you have to run the command:

rake db:rollback
Enter fullscreen mode Exit fullscreen mode

Adding and Removing columns

Ex:
rails g migration AddImageToPosts
    OR
rails g migration RemoveExpiresOnFromPosts
Enter fullscreen mode Exit fullscreen mode
  • If your database gets into a weird state (usually caused by deleting old migration files), your ultimate last resort is
  • This will destroy your entire database and all the data within it. Then, you can fix your migrations and re-run all from scratch with rake db:migrate, then rake sample_data to recover the sample data.
rake db:drop
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs