现有列的change_column_null [英] change_column_null for existing column
问题描述
我试图更改:profiles
表上现有列:access_titles
上布尔属性的nil
可能性.该列之所以存在是因为进行了迁移:
I'm attempting to change the nil
possibility of a boolean attribute on the existing column :access_titles
on the :profiles
table. That column exists because of this migration:
class AddAccessItemsToProfiles < ActiveRecord::Migration
def self.up
add_column :profiles, :access_items, :boolean, :default => true
end
def self.down
remove_column :profiles, :access_items, :boolean, :default => nil
end
end
要更改nil
,我尝试像往常一样生成迁移:
To change nil
, I tried generating a migration as I always have:
rails g migration ChangeColumnNull :profiles :access_items :null => false
但是那什么也没做,所以我做了一个独立的迁移:
But that did nothing, so I did a standalone migration:
rails g migration AddChangeColumnNullToAccessItems
在其中我添加了:
class AddChangeColumnNullToAccessItems < ActiveRecord::Migration
def self.up
change_column_null :profiles, :access_items, :boolean, false
end
def self.down
change_column_null :profiles, :access_items, :boolean, true
end
end
然后我运行了rake db:migrate
,重新启动了服务器,未发现任何更改.所以我尝试了:
I then ran rake db:migrate
, restarted my server and saw no changes. So I tried:
class AddChangeColumnNullToAccessItems < ActiveRecord::Migration
def self.up
change_column_null :profiles, :access_items, false
end
def self.down
change_column_null :profiles, :access_items, true
end
end
然后做同样的事情:rake db:migrate
,重新启动服务器,没有任何改变.
Then did the same thing: rake db:migrate
, restarted the server, and nothing changed.
我做错了什么?我希望只将:access_items
的布尔值设为true和false,而不必转储数据库.
What am I doing wrong? I was hoping to only have the boolean value of :access_items
be true and false without having to dump the database.
更新:尝试change_column_null :profiles, :access_items, false
我遇到错误:
-- change_column_null(:profiles, :access_items, false)
rake aborted!
An error has occurred, this and all later migrations canceled:
PGError: ERROR: column "access_items" contains null values
: ALTER TABLE "profiles" ALTER "access_items" SET NOT NULL
因此,根据以下建议,我必须在迁移中插入change_column_null :profiles, :access_items, false, true
.
So, per the advice below I had to insert change_column_null :profiles, :access_items, false, true
into my migration.
推荐答案
您可以使用:
change_column_null :profiles, :access_items, false, 1
第四个参数是可选的,它允许您设置列的默认值.当您在列中包含空值并将空值设置为false
时,这是必需的.
The fourth parameter is optional and allows you to set the default value for the column. This is required when you have nulls in a column and you're setting the null value to false
.
这篇关于现有列的change_column_null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!