I’m noting down some of the points that I come across while learning rails migrations
Migrations should not be repeated, and each migration should have coded delete for all that was created.
ie, in a similar way when we create a migration, there is a self.up and self.down defined in the Migration class, we should also create self.down for all sort of creations or insertions into the database via Migrations.
While implementing a HABTM ( has and belongs to many ) relationship, the intermediate database that serves as the link between two databases with HABTM should not have PRIMARY ID. To make the database table without primary id we should code the Migration file like this…
class BlogsTags < ActiveRecord::Migration def self.up create_table :blogs_tags, :id => false do |t| t.integer :blog_id t.integer :tag_id end end def self.down drop_table :blogs_tags end end
Here, we are connecting two tables Blogs and Tags with HABTM relationship.
by naming convention Blog comes first to Tags, so the name of the intermediate Table should be Blogs_Tags
:id => false , makes the table without PRIMARY ID ( this is mandatory for an intermediate table of a HABTM relationship.
Why self.drop is important ?
Migrations are made with filenames specifying the time of creation of a Migration. Rails is providing us facility of reverting back actions we have done on the tables using that datetime. For that purpose, rails adds self.drop method which tells how to revert back. While we are creating Migrations by ourself coding, we should also write the code in self.drop to revert all actions we have done on the database, so that rails can help us rectify any error.