Pirun Seng

Ruby on Rails Developer

Common Mistakes We Might Make in Rails Development

1 - Irreversible Migration

Rails 3 has introduced change method which help reduces lines of migration code from two method up and down to just one which is change method. For example, we want to change default value of nil to an empty string ''.

1
2
3
def change
  change_column_default :articles, :owner, ''
end

There is no problem when we run rake db:migrate. Yet, we don’t realize that we have made a mistake until we rollback the migration at some point. Then there will be an exception of ActiveRecord::IrreversibleMigration.

To get rid of the ActiveRecord::IrreversibleMigration exception, we have to rewrite both up and down methods again.

1
2
3
4
5
6
7
def up
  change_column_default :articles, :owner, ''
end

def down
  change_column_default :articles, :owner, nil
end

Heh! If you’re using Rails 5, there is a better way that help improve this case by adding from (old default value or nil) and to (new default value) options.

1
2
3
def change
  change_column_default :articles, :owner, from: nil, to: ''
end

By specifying the from and to options, we can freely run our migrations up and down without getting any of ActiveRecord::IrreversibleMigration exceptions anymore.

2 - Accidentally Deleted Object(s)

To be continued…