Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change column name Rails

Tags:

I have this table:

class CreateShoes < ActiveRecord::Migration   def change     create_table :shoes do |t|       t.string :name       t.boolean :leather       t.integer :season        t.timestamps null: false     end   end end 

the 'season' column should be called 'season_id'. I know that I have to write 't.rename :season, :season_id' as explained in http://edgeguides.rubyonrails.org/active_record_migrations.html#column-modifiers but I don't manage to find the right syntax. Should it be?

class CreateShoes < ActiveRecord::Migration   def change     create_table :shoes do |t|       t.string :name       t.boolean :leather       t.integer :season        t.timestamps null: false     end      change_table :products do |t|       t.rename :season, :season_id     end    end end 

Doesn't work. Anything I have to do in the Mac console? Thanks!

like image 1000
Pere Avatar asked Jan 14 '16 17:01

Pere


People also ask

How do I rename a column in 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 ...

Can I rename a migration file rails?

You can change the migration file name, but you have to perform a few steps: rake db:rollback to the point that queries table is rolled back. Now change the name of migration file, also the contents. Change the name of any Model that may use the table.


1 Answers

Run in your console:

$ rails g migration rename_season_to_season_id 

Now file db/migrate/TIMESTAMP_rename_season_to_season_id.rb contains following:

class RenameSeasonToSeasonId < ActiveRecord::Migration   def change   end end 

Modify it as follows:

class RenameSeasonToSeasonId < ActiveRecord::Migration   def change     rename_column :shoes, :season, :season_id   end end 

Then run $ rake db:migrate in console.

like image 197
Inpego Avatar answered Oct 01 '22 23:10

Inpego