添加 :default =>现有 Rails 列中的布尔值 true [英] Adding :default => true to boolean in existing Rails column

查看:22
本文介绍了添加 :default =>现有 Rails 列中的布尔值 true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一些问题(即 这个)在这里关于向现有列添加默认布尔值.所以我尝试了 change_column 的建议,但我一定没有做对.

I've seen a few questions (namely this one) here on SO about adding a default boolean value to an existing column. So I tried the change_column suggestion but I mustn't be doing it right.

我试过了:

$ change_column :profiles, :show_attribute, :boolean, :default => true

返回 -bash: change_column: command not found

然后我跑了:

$ rails g change_column :profiles, :show_attribute, :boolean, :default => true

...和

$ rails change_column :profiles, :show_attribute, :boolean, :default => true

然后运行 ​​rake db:migrate,但 :show_attribute 的值仍然是 nil.在我上面提到的问题中,它在 PostgreSQL 中说您需要手动更新它.由于我使用的是 PostgreSQL,因此我在 create_profiles 迁移中添加了以下内容:

Then ran rake db:migrate, but the value for :show_attribute remained nil. In the question I referenced above it says in PostgreSQL you need to update it manually. Since I'm using PostgreSQL I added the following in my create_profiles migration:

t.boolean :show_attribute, :default => true

谁能告诉我我在这里做错了什么?

Can someone tell me what I'm doing wrong here?

推荐答案

change_columnActiveRecord::Migration的一个方法,所以不能这样调用在控制台中.

change_column is a method of ActiveRecord::Migration, so you can't call it like that in the console.

如果要为此列添加默认值,请创建一个新的迁移:

If you want to add a default value for this column, create a new migration:

rails g 迁移 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 任务 或直接进入 rails 控制台 并更新所有记录(我不建议在生产环境中这样做).

It won't change anything to the already created records. To do that you would have to create a rake task or just go in the rails console and update all the records (which I would not recommend in production).

当你添加 t.boolean :show_attribute, :default =>truecreate_profiles 迁移,预计它没有做任何事情.仅执行尚未运行的迁移.如果你从一个新的数据库开始,那么它会将默认设置为 true.

When you added t.boolean :show_attribute, :default => true to the create_profiles migration, it's expected that it didn't do anything. Only migrations that have not already been ran are executed. If you started with a fresh database, then it would set the default to true.

这篇关于添加 :default =>现有 Rails 列中的布尔值 true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆