I\'m terrible at naming and realize that there are a better set of names for my models in my Rails app.
Is there any way to use a migration to rename a model and its cor
Here's an example:
class RenameOldTableToNewTable < ActiveRecord::Migration
def self.up
rename_table :old_table_name, :new_table_name
end
def self.down
rename_table :new_table_name, :old_table_name
end
end
I had to go and rename the model declaration file manually.
Edit:
In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder
knows how to reverse rename_table migrations, so you can do this:
class RenameOldTableToNewTable < ActiveRecord::Migration
def change
rename_table :old_table_name, :new_table_name
end
end
(You still have to go through and manually rename your files.)
The other answers and comments covered table renaming, file renaming, and grepping through your code.
I'd like to add a few more caveats:
Let's use a real-world example I faced today: renaming a model from 'Merchant' to 'Business.'
In Rails 4 all I had to do was the def change
def change
rename_table :old_table_name, :new_table_name
end
And all of my indexes were taken care of for me. I did not need to manually update the indexes by removing the old ones and adding new ones.
And it works using the change for going up or down in regards to the indexes as well.
You also need to replace your indexes:
class RenameOldTableToNewTable< ActiveRecord:Migration
def self.up
remove_index :old_table_name, :column_name
rename_table :old_table_name, :new_table_name
add_index :new_table_name, :column_name
end
def self.down
remove_index :new_table_name, :column_name
rename_table :new_table_name, :old_table_name
add_index :old_table_name, :column_name
end
end
And rename your files etc, manually as other answers here describe.
See: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
Make sure you can rollback and roll forward after you write this migration. It can get tricky if you get something wrong and get stuck with a migration that tries to effect something that no longer exists. Best trash the whole database and start again if you can't roll back. So be aware you might need to back something up.
Also: check schema_db for any relevant column names in other tables defined by a has_ or belongs_to or something. You'll probably need to edit those too.
And finally, doing this without a regression test suite would be nuts.
You can do execute this command : rails g migration rename_{old_table_name}to{new_table_name}
after you edit the file and add this code in the method change
rename_table :{old_table_name}, :{new_table_name}