ruby-on-railsdatabaserails-console

Ruby on rails updating model via rails console


I have run rails g model Task description:text. Then I have run rails console and put in a few tasks. I would now like to add more attributes to the create_tasks.rb file. Such as .string :title.

What I tried:

  1. opened the file(create_tasks.rb), put the new line in. Then ran rake db:migrate then went back into the console and opened the first task and it doesn't show the title attribute.
  2. also tried creating a new task using the title attribute. Error: unknown title attribute for Task.

So, how do I update the model?


Solution

  • You need to rails db:rollback to roll the database back before the latest migration, add the new variables to the migration file, then run rails db:migrate to have the new parts of the migration file included.

    If you need to roll back more revisions (if you have created more migrations since you created this model), you can either include the number of roll backs like

    rails db:rollback STEP=<enter number of steps>
    #e.g. rails db:rollback STEP=2
    

    or, you could also rails db:reset which would remove all databases, recreate them, then remigrate them. Or you could rails db:drop to drop the database, then rails db:create and rails db:migrate to migrate the new database.

    Do not edit the schema file. The schema file is automatically updated when you run migrations etc to match the content of your migration files.