BC2
BC2

Reputation: 1129

How to update database schema without losing original data

Hi guys I would like to know if there's a way not to lose the data if you're trying to rollback your migration just to update the schema ? For example after running rake db:migrate, and after few rounds of data inserted, you want to add in a new attribute to the schema.

So my question is how can i add the new attribute without losing my previous record ? is it possible to do so ? Because all this while i just did by running rake db:rollback STEP= ... and lost all the data i've generated. Just wondering.

Thanks for helping From: BC2

Upvotes: 1

Views: 2990

Answers (2)

simanchala
simanchala

Reputation: 127

if you have an existing table and want to add new attribute in existing table then simple write stand alone migration.
for ex: you have a students table with attribute name, roll_no ... and now u want to add 'address' attribute in students table

$ rails generate migration AddAddressToStudents address:string

will generate

    class AddAddressToStudents < ActiveRecord::Migration
      def change
        add_column :students, :address, :string
      end
    end

then simply run "rake db:migrate"

Upvotes: 4

manishie
manishie

Reputation: 5322

You don't need to rollback to update the schema. Just write a new migration to update the existing table.

For example, to add a field to your user table without destroying anything, write a migration like:

class AddFieldsToUser < ActiveRecord::Migration
  def change
    change_table :users do |t|
      t.date :birthday         # add new field
      t.remove :first          # remove a field
      t.rename :gender, :sex   # rename a field      

    end

  end
end

See here for more info: http://guides.rubyonrails.org/migrations.html#changing-tables

Upvotes: 2

Related Questions