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

时间:2017-03-08 10:10:13

标签: ruby-on-rails ruby activerecord migration rails-activerecord

我尝试将默认列值从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

2 个答案:

答案 0 :(得分:8)

很奇怪,因为根据文档(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 :(得分: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

我希望这种解释将有助于人们在其他答案下发表评论。

相关问题