使用迁移更改表列的默认值

问题描述 投票:5回答:2

我尝试将默认列值从false更改为true。但是当我运行rake db:migrate VERSION=904984092840298时,我得到了以下错误。

StandardError: An error has occurred, this and all later migrations canceled:

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for type boolean: "---
:from: false
:to: true
"
: ALTER TABLE "plussites" ALTER COLUMN "hide_season_selector" SET DEFAULT '---
:from: false
:to: true
'

移民

class ChangeDefaultvalueForHideSeasonSelector < ActiveRecord::Migration 
  def change 
    change_column_default :plussites, :hide_season_selector, from: false, to: true 
  end
end
ruby-on-rails ruby activerecord migration rails-activerecord
2个回答
12
投票

这很奇怪,因为根据文档(change_column_default)你的代码应该工作..

作为选项,您可以定义updown

class ChangeDefaultvalueForHideSeasonSelector < ActiveRecord::Migration
  def up
    change_column_default :plussites, :hide_season_selector, true
  end

  def down
    change_column_default :plussites, :hide_season_selector, false
  end
end

1
投票

您必须检查您正在使用的ActiveRecord版本。根据你的命令rake db:migrate,你仍然在轨道4.2或更早。

如果您使用的ActiveRecord最高为4.2(change_column_default 4.2.9),则没有from / to选项,您只能将新的默认选项定义为param。

class ChangeDefaultvalueForHideSeasonSelector < ActiveRecord::Migration 
  def change 
    change_column_default :plussites, :hide_season_selector, true 
  end
end

上面的解决方案将不允许回滚,因为该方法不知道,以前的默认值是什么。这就是为什么你必须定义一个单独的向上和向下方法:

class ChangeDefaultvalueForHideSeasonSelector < ActiveRecord::Migration
  def up
    change_column_default :plussites, :hide_season_selector, true
  end

  def down
    change_column_default :plussites, :hide_season_selector, false
  end
end

如果您在轨道5或更新轨道上,则有新的可能性来定义之前的值以及之后应该从/到(change_column_default 5.0.0.1)之后的值。在轨道5上,您可以使用您选择的解决方案:

class ChangeDefaultvalueForHideSeasonSelector < ActiveRecord::Migration 
  def change 
    change_column_default :plussites, :hide_season_selector, from: false, to: true 
  end
end

我希望这个解释能够帮助那些在另一个答案下发表评论的人。

© www.soinside.com 2019 - 2024. All rights reserved.