我在这里看到了一些关于向现有列添加默认布尔值的问题(即this one)。所以我尝试了change_column
的建议,但我肯定做得不对。
我试过了:
$ change_column :profiles, :show_attribute, :boolean, :default => true
它返回-bash: change_column: command not found
然后我运行:
$ rails g change_column :profiles, :show_attribute, :boolean, :default => true
...and
$ rails change_column :profiles, :show_attribute, :boolean, :default => true
然后运行rake db:migrate
,但:show_attribute
的值仍然是nil
。在我上面提到的问题中,它说在PostgreSQL中你需要手动更新它。由于我使用的是PostgreSQL,所以我在create_profiles
迁移中添加了以下内容:
t.boolean :show_attribute, :default => true
有人能告诉我我哪里做错了吗?
发布于 2011-12-25 06:20:05
change_column
是ActiveRecord::Migration
的一个方法,所以你不能在控制台这样调用它。
如果要为该列添加默认值,请创建新迁移:
rails g migration add_default_value_to_show_attribute
然后在创建的迁移中:
# That's the more generic way to change a column
def up
change_column :profiles, :show_attribute, :boolean, default: true
end
def down
change_column :profiles, :show_attribute, :boolean, default: nil
end
或者更具体的选项:
def up
change_column_default :profiles, :show_attribute, true
end
def down
change_column_default :profiles, :show_attribute, nil
end
然后运行rake db:migrate
。
它不会对已创建的记录进行任何更改。要做到这一点,您必须创建一个rake task
,或者直接在rails console
中更新所有记录(我不建议在生产环境中这样做)。
当您将t.boolean :show_attribute, :default => true
添加到create_profiles
迁移中时,预计它不会执行任何操作。仅执行尚未运行的迁移。如果您从一个新的数据库开始,那么它会将缺省值设置为true。
发布于 2013-10-16 15:16:49
作为公认答案的变体,您还可以在迁移中使用change_column_default
方法:
def up
change_column_default :profiles, :show_attribute, true
end
def down
change_column_default :profiles, :show_attribute, nil
end
发布于 2016-05-07 05:13:25
我不确定这是什么时候写的,但目前要在迁移中添加或删除列中的默认值,您可以使用以下命令:
change_column_null :products, :name, false
Rails 5:
change_column_default :products, :approved, from: true, to: false
http://edgeguides.rubyonrails.org/active_record_migrations.html#changing-columns
Rails 4.2:
change_column_default :products, :approved, false
http://guides.rubyonrails.org/v4.2/active_record_migrations.html#changing-columns
这是避免在迁移或模式中查找列规范的一种巧妙方法。
https://stackoverflow.com/questions/8627156
复制相似问题