可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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