tim_xyz tim_xyz - 4 months ago 12
Ruby Question

What is the difference between `rename_column` in self.up v self.down (Rails)

What is the difference between

rename_column
in
self.up
v
self.down
?

I have a migration file that looks like below:

def self.up
rename_column :posts, :title, :subject
end

def self.down
rename_column :posts, :subject, :title
end


Until now I've only seen
def change
in migration files. Not
self.up
and
self.down
.

I can see how this would make sense if one was
remove_column
and one was
add_column
- to simulate a
rename_column
, with the added benefit of being able to alter the datatype, etc.

But I don't see why
rename
would be required twice. What is going on here?

Answer

rename_column is used in both up and down because there's no need to change any of the column details other than the name. Both title and subject are relatively short, text-based values. If you dropped a column and added a new one, you'd just be using the same datatype and other attributes. Renaming a column is simply more expedient in this case.

Just because you're changing a column doesn't imply that you have to change everything about it.

Comments