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?
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.
Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns. Foreign keys - These fields should be named following the pattern singularized_table_name_id (e.g., item_id , order_id ).
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 ...
ORM is Object Relational Mapper. It means you don't have to manually call the database yourself; the ORM handles it for you. Ruby on Rails uses one called ActiveRecord, and it's a really good one. ORM allows you to do things such as: User.
I figured out the following way:
1, generate migration file:
rails generate migration rename_cars_to_trains
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
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...
I would recommend the following:
Change manually the Active Record model class into Train
Make migration to change the database table name from cars to trains
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With