Writing database queries can be a pain, right? On top of that, imagine when you shift from using one database to another. That's where migrations come to the rescue, you write them once and let it do all the heavy loading for you!
If you have used rails, you probably have seen the migration files. Each migration file can be thought of as a version of the database. Each time you write a new migration file to do some changes, you need to execute the command below which applies those changes to the database.
I'll be listing some of the commands that I found useful while working on Rails 4.2, one of which would be to create the foreign key reference. this is extremely useful when you make belongs_to and has_many associations.
Let's say Stark has_many IronmanSuits, and IronmanSuits belong_to Stark.
The above command will create a migration file, which upon database migration will create a foreign key named stark_id in ironman_suits table. You can also create your own migration classes to do the same things. Lets say we need to remove the repulsor column from the ironman_suits table:
class RemoveRepulsorFromIronmanSuits < ActiveRecord::Migration
def change
remove_column :ironman_suits, :repulsor, :string
end
end
Lets say you named one of the weapon columns in ironman_suits table as missiles but now you want to rename it to rockets, this is how you'll write a migration file to do just that:
class RenameMissilesToRocketsInIronmanSuits < ActiveRecord::Migration
def change
rename_table :missiles, :rockets
end
end
If you have used rails, you probably have seen the migration files. Each migration file can be thought of as a version of the database. Each time you write a new migration file to do some changes, you need to execute the command below which applies those changes to the database.
$ rake db:migrate
I'll be listing some of the commands that I found useful while working on Rails 4.2, one of which would be to create the foreign key reference. this is extremely useful when you make belongs_to and has_many associations.
Let's say Stark has_many IronmanSuits, and IronmanSuits belong_to Stark.
$ bin/rails generate migration add_stark_to_ironman_suits stark:referencesThe above command will create a migration file, which upon database migration will create a foreign key named stark_id in ironman_suits table. You can also create your own migration classes to do the same things. Lets say we need to remove the repulsor column from the ironman_suits table:
class RemoveRepulsorFromIronmanSuits < ActiveRecord::Migration
def change
remove_column :ironman_suits, :repulsor, :string
end
end
Lets say you named one of the weapon columns in ironman_suits table as missiles but now you want to rename it to rockets, this is how you'll write a migration file to do just that:
class RenameMissilesToRocketsInIronmanSuits < ActiveRecord::Migration
def change
rename_table :missiles, :rockets
end
end
No comments:
Post a Comment