Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference in using up/down vs change/reversible methods in Rails migrations?

In a Rails migration, does it make any difference, if I do this:

def up
  foo
end

def down
  bar
end

or this:

def change
  reversible do |direction|
    direction.up { foo }
    direction.down { bar }
  end
end

?

I think that it's better to use the change method if part of the migration includes reversible methods, such as create_table, add_column etc.. Other than that, is there any difference?

like image 960
Alexander Popov Avatar asked Jan 17 '26 06:01

Alexander Popov


1 Answers

As you show it, there is no advantage. The main advantage is that a lot of the time you don't need to write the down method / block at all, eg

class SomeMigration < ActiveRecord::Migration
  def change
    create_table :articles do |t|
      ...
    end
  end
end

The reversible method is mostly used when there is a small part of a migration that activerecord doesn't know how to reverse (eg a raw SQL statement)

like image 148
Frederick Cheung Avatar answered Jan 19 '26 20:01

Frederick Cheung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!