DEV Community

Cover image for Rails Migration Hacks !! Things You should know if you are a ROR Developer .
Sambit Mohanty
Sambit Mohanty

Posted on • Updated on

Rails Migration Hacks !! Things You should know if you are a ROR Developer .

So here is my first post, before i start something let me give a brief summary about me. So i am a software engineer by profession and i am here to share experience which i have faced yet. so today our topic is "RAILS MIGRATION".

If you are reading this then i assume that you are familiar with this term , what it is? and why we use it? so let's skip this part and move on.

1. The way to create migration files???

So the syntax for creating migration file is:-

   rails g migration add_column_to_shops title:string description:text
   rails g migration AddColumnToShop title:string description:text

2. What if i want to change something in my migration file???

So the correct way to do it is :-
step - 1:-

rails db:migrate:down VERSION=20121212123456

Step - 2:-
change whatever you want to change inside change method, then save it

class AddDetailsToProducts < ActiveRecord::Migration[6.0]
  def change
    add_column :products, :price, :decimal
  end
end

step - 3:-

rails db:migrate:up VERSION=20121212123456

Voillaaaa!!! the migration file got changed and it updates on schema file also .

3. Is it okay if i delete the old migration???

So the answer is no, You should never change your old migrations. If you realised that given column is unnecessary, write a new migration to remove it.

If you are working in a team, the fact that you removed the migration won't change your teammates' schemas. Even more, they have no migration to revert now!

4. What is the datatypes we can write when we are declaring column name in migration file??

:binary, :boolean, :date, :datetime, :decimal, :float, :integer,:primary_key, :string, 
:text, :time, :timestamp

source:- https://guides.rubyonrails.org

5. If you by mistakenly done db:migrate then how to revert back???

   rails db:rollback (it will revert the latest migration)
   rake db:rollback STEP=3 (it will revert last 3 migration file)

6. What are the change methods we can do it using rails migration???

a. Change Table Name:-

    class ChangeTableName < ActiveRecord::Migration[6.0]
      def change
        rename_table :old_table_name, :new_table_name
      end
    end

b. Change Column Name:-

    class ChangeColumnName < ActiveRecord::Migration[6.0]
      def change
        rename_column :table_name, :old_column, :new_column
      end
    end

c. Create Table

    class ChangeColumnName < ActiveRecord::Migration[6.0]
      def change
          create_table :contents do |t|
             t.string "title"
             t.timestamps
          end
      end
    end

d. Drop Table

      class DropTableName < ActiveRecord::Migration
        def up
          drop_table :table_name
        end

        def down
          raise ActiveRecord::IrreversibleMigration
        end
      end

So these are the basic change methods what we do in our daily basis, there is many more change methods but usually these 4 are used in professional level.

Bonus Tips

If You are using rails engine in your project then how to copy migration file from rails engine to your main app???
.
think????
.
.
.
.
think again???
.
.
.
.
So you have to add this magic command in your main app

   rails engine_name:install:migrations

that will do the trick.....

So that's it for today. If i miss something from rails migration section, please let me know in comment section.

Top comments (8)

Collapse
 
olivierjm profile image
Olivier JM Maniraho

Nicely written article, I wish I saw this just a fee days ago.

I am new in a rails world and I recently messed up my migrations, I didnt know that you have to migrate up on a specific migration version after doing a migration down.

Quick question, the irreversible on Active record, does that mean I can still rollback to previous versions?
What is the most recommended way of cleaning up issues with migrations especially when you have rolled back already?
Looking forward to more of these articles

Collapse
 
sambitmohanty954 profile image
Sambit Mohanty • Edited

in api.rubyonrails.org/classes/Active... website written:-

"Some transformations are destructive in a manner that cannot be reversed. Migrations of that kind should raise an ActiveRecord::IrreversibleMigration exception in their down method."

But there is way you can reverse it????

you can reverse it by using "Reversible" , basically this method allow you to specify up and down behavior for part of the migration. so in Reversible part you can write your your own method

class MigartionFileName < ActiveRecord::Migration[6.0]
  def change

    reversible do |var|
      var.up do
        --------your up method------
      end

      var.down do
       -------your down method-----
      end

    end
  end
end

thanks for your comment , stay tuned for more interesting topic . if you want something that i cover on my ruby on rails blog then please do let me know . _^

Collapse
 
storrence88 profile image
Info Comment hidden by post author - thread only accessible via permalink
Steven Torrence

For step 3 - Is it still supposed to be migrate down? Or do we migrate up?

rails db:migrate:down VERSION=20121212123456
Collapse
 
sambitmohanty954 profile image
Sambit Mohanty

actually it's not down it's migrate up. sorry its just a silly mistake from my side.

Collapse
 
andrewleontev profile image
Andrey Leontev

What the difference between

rails db:migrate:down VERSION=20121212123456
and
rails db:migrate VERSION=20121212123456

Collapse
 
sambitmohanty954 profile image
Sambit Mohanty

using rails db:migrate:down/up VERSION=20121212123456 , you can specifically perform up and down migration but if you are using rails db:migrate VERSION=20121212123456
then it by default do only up for that specific version of migration file.

Thanks for your valuable comment

Collapse
 
bachdx2812 profile image
bachdx

I really hate it everytime i made mini mistake and have to make a file to fix it. So i found this to manage migration in rails and it quite great. take a look!
github.com/winebarrel/ridgepole

Collapse
 
sambitmohanty954 profile image
Sambit Mohanty

Thank you bachdx for sharing this link . It's a treasure for me ^_^

Some comments have been hidden by the post's author - find out more