添加:default =>在现有的Rails列中为boolean为true [英] Adding :default => true to boolean in existing Rails column
问题描述
我看到了一些问题(即 )在这里,关于向现有列添加默认布尔值.所以我尝试了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 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
并更新所有记录.
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.
将t.boolean :show_attribute, :default => true
添加到create_profiles
迁移中时,如果不执行任何操作是正常的.仅执行尚未运行的迁移.如果您从一个全新的数据库开始,那么它将默认设置为true.
When you added t.boolean :show_attribute, :default => true
to the create_profiles
migration, it's normal if 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列中为boolean为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!