Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write a migration to rename an ActiveRecord model and its table in Rails?

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 corresponding table?

like image 892
readonly Avatar asked Jan 23 '09 00:01

readonly


People also ask

How do you name migration in rails?

Migrations should be: Camel cased or Snake cased. start with an action (i.e. create, add, remove, etc) The name of the table should be the last word and it should be plural.

How do I change the model name in Ruby?

If you're using RubyMine, go into the model, right click the class name > refactor and change the name. RubyMine will refactor everything and create a new migration for the database as well.

How do I change migration in rails?

Go to /db/migrate folder and edit the migration file you made.


1 Answers

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.)

like image 99
readonly Avatar answered Oct 13 '22 00:10

readonly