简体   繁体   中英

rails database migration issue

Ok so you've built your model 'rails generate model test (inputs)' you've rake db:migrate checked your schema file all looks good and working and writing to sqlite. But then you realise you need another attribute in the DB. One way is to rake db:rollback, make change in the migrate file, rake db:migrate again and hey presto all looking good. However doing rake db:rollback has lost all my data already stored in the sqlite. So I'm guessing this is not the correct way to do this? What is the best way?

class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
  t.text :title
  t.text :requester
  t.text :requester_email
  t.text :customer
  t.text :contact
  t.text :customer_email
  t.text :customer_phone
  t.string :type_of_change

You can generate a new migration with rails g migration <migration_name> (eg. rails g migration add_foo_to_blah ) and then inside that new migration, make the changes you need.

eg. you can add new columns, rename columns, etc.

For more information: http://guides.rubyonrails.org/migrations.html#creating-a-standalone-migration

Yes, db:rollback takes back the last migration, so if in last migration you added some columns, db:rollback will remove them (and if you change the migration and run it again, these fields will be added, but data is already lost).

The proper way to add more fields is to generate new migration and add these fields there.

In fact db:rollback is best way. Of course when you do db:rollback it will wipe away your existing data,but you need to do db:migrate to get the data appear again in the tables.

If you don't want to do rake db:rollback ,then create another migration file which will do the job for you.

Edit

You need to perform the below command to get that column added in your posts table.

rails g migration AddImplementerToPosts implementer:text

and do rake db:migrate to make sure that column added in your table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM