添加:默认 =>true 为现有 Rails 列中的布尔值
我看到了一些问题(即这个)在这里关于向现有列添加默认布尔值.所以我尝试了 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_column
是 ActiveRecord::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 =>对于
,预计它什么也没做.仅执行尚未运行的迁移.如果您从一个全新的数据库开始,那么它会将默认值设置为 true.create_profiles
迁移来说是真的
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.