Mellon
Mellon

Reputation: 38902

How to re-name a ActiveRecord Model which can automatically change the table name in DB?

I have a Active Record model "car", I would like to change the name of this model to "train" without changing functionalities inside, that's only change the name. Also, the table name should be changed to "trains".

Is there any rails command can do that at onece? Or I have to manually change the name in side the class or migration? If I have to change manually, it's gonna be complicated, because I have to also change other models which have associations to my "car" model.

Any good suggestions?

Upvotes: 16

Views: 25599

Answers (4)

hade
hade

Reputation: 1715

I would recommend the following:

  1. Change manually the Active Record model class into Train

  2. Make migration to change the database table name from cars to trains

  3. Make good search to change references from Car to Train.

If you have constantly the need to change database table names, you might want to reconsider naming the tables more abstact way. Like in this case you could have table called vehicles and have the "type" field specifying the type (for instance: car or train).

Upvotes: 19

JuJoDi
JuJoDi

Reputation: 14975

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.

Upvotes: 1

Mellon
Mellon

Reputation: 38902

I figured out the following way:

1, generate migration file:

rails generate migration rename_cars_to_trains
  1. edit the created migration file to:

    class RenameCarsToTrains < ActiveRecord::Migration
      def self.up
        rename_table :cars, :trains
      end
    
      def self.down
        rename_table :trains, :cars
      end
    end
    
  2. rake db:migrate

After these steps, the table name changed from cars to trains, then, I have to manually change the controller and views names and the associations...

If you have any more efficient way, let me know...

Upvotes: 39

Omer Aslam
Omer Aslam

Reputation: 4874

I used following steps to rename my model

In sublime text:

  1. press cmd + shift + find and choose case-sensitive search (see left buttons). It will search word in whole project
  2. search and replace 'Cars' to 'Trains'
  3. search and replace 'Car' to 'Train'
  4. search and replace 'car' to 'train'
  5. rails generate migration rename_cars_to_trains
  6. manually change following file names

    • cars_controller
    • car_helper
    • Model/ car.rb
    • all related files in test folder
  7. change folder name in views: cars to trains

Upvotes: 3

Related Questions