Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the name of a database model and table in Rails?

Lots out there about changing model names only or mapping new models to existing tables, but nothing about renaming both at the same time. For now, I'm starting with the DB table and working my way out with Find/Replace in my code, but I'm surprised there isn't something better or at least someone who's tried it and written about it.

like image 954
kbighorse Avatar asked Jul 14 '10 00:07

kbighorse


People also ask

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 you change the name of a column in Ruby on Rails?

If you happen to have a whole bunch of columns to rename, or something that would have required repeating the table name over and over again: rename_column :table_name, :old_column1, :new_column1 rename_column :table_name, :old_column2, :new_column2 ...


1 Answers

The full list of things to rename are:

  1. table name
  2. foreign key column names in associations (model_id columns)
  3. model file name in app/models/
  4. class name in app/models/model.rb
  5. associations in other models (has_one/has_many)
  6. controller file name in app/controllers/
  7. class name in app/controllers/models_controller.rb
  8. folder name in app/views/
  9. resource route in config/routes.rb
  10. fixture file name in test/fixtures/
  11. references to the model in associated fixtures in test/fixtures/
  12. unit test file name in test/unit/
  13. class name in test/unit/model_test.rb
  14. controller test file name in test/functional/
  15. class name in test/functional/models_controller_test.rb
  16. find/replace the class name anywhere in your code

You should write a migration for the database changes. The rest can be done easily, or you can use your IDE (RadRails/RubyMine) to help. I guess there's no built in function because there's no way to know where in your code you've used the model.

like image 62
Andrew Vit Avatar answered Nov 09 '22 00:11

Andrew Vit