首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将:default => true添加到现有Rails列中的布尔值

将:default => true添加到现有Rails列中的布尔值
EN

Stack Overflow用户
提问于 2011-12-25 06:15:28
回答 6查看 138K关注 0票数 164

我在这里看到了一些关于向现有列添加默认布尔值的问题(即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

有人能告诉我我哪里做错了吗?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2011-12-25 06:20:05

change_columnActiveRecord::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。

票数 322
EN

Stack Overflow用户

发布于 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

Rails API-docs

票数 96
EN

Stack Overflow用户

发布于 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

这是避免在迁移或模式中查找列规范的一种巧妙方法。

票数 36
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8627156

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档