change column name Rails

匿名 (未验证) 提交于 2019-12-03 02:50:02

问题:

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!

回答1:

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.



回答2:

Either fix your migration and do

rake db:rollback db:migrate 

or make another migration like so:

rename_column :shoes, :season, :season_id if column_exists?(:shoes, :season) && !column_exists?(:shoes, :season_id) 

and then do

rake db:migrate 


回答3:

If your intention is to rename column in table than you example migration is not making sense :)... Instead of this

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 

You just need table change migration, like this(Rails will take care rollback for your):

class RenameSessionColumnInsideShoes < ActiveRecord::Migration   def change     change_table :products do |t|       t.rename :season, :season_id     end   end end 

rename method on table object in rails is valid method, as you can see in Rails source code

https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb#L582



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!