Hello,
I am new bee to Rails and I am really in a dilemma of follwing task:
I have some existing migrations and going to use some more new
migrations, and I have few common fields which is not covered in my
existing(old) migrations. Now I want some way to add this common fields
with my existing as well as new migrations without writing any extra
migration script.
shall I need to use generators, if yes then how?
also please let me know what is the best way to achieve this.
I will b e really thanful if someone could really help me out of this.
I have some existing migrations and going to use some more new
migrations, and I have few common fields which is not covered in my
existing(old) migrations. Now I want some way to add this common fields
with my existing as well as new migrations without writing any extra
migration script.
shall I need to use generators, if yes then how?
also please let me know what is the best way to achieve this.
If I understand you correctly you are asking how to add/remove fields
from existing database tables using migrations.
This guide explains pretty much everything you need to know about Rails
migrations:
This sections specifically explains how to change tables using
migrations:
Keep in mind that the purpose of migrations is to support an agile
design methodology to database design. It’s very common to need to add
new columns, remove columns or rename columns in your database as you
progress the design of your application.
There is also a special convention for adding/removing columns to a
table using generators.
class AddPartNumberToProducts < ActiveRecord::Migration
def self.up
add_column :products, :part_number, :string
end
def self.down
remove_column :products, :part_number
end
end
Notice that any changes made in self.up gets undone in self.down. One
key to good migrations is to make sure “down” always reverses the
changes made in “up.” This allows you to rollback schema changes without
causing adverse effects.
In some cases (especially with the production environment) this may
require data migration along with schema migration. For example if you
find you need to normalize a table you may have to move the data into
the new schema while making the schema changes. Its up to you to make
sure reversing that process occurs in the proper order to avoid any data
loss. If this is required make sure you do sufficient testing before
running these migrations on production data.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.