使用 Rails 和 Postgresql 进行迁移时未填充默认值
我目前正在尝试运行此迁移:
class AddDroppedProjectsCountToUser < ActiveRecord::Migration
def self.up
add_column :users, :dropped_projects, :integer, {:default=>0, :required=>true}
end
def self.down
remove_column :users, :dropped_projects
end
end
该列已正确添加,但没有任何旧记录填充为 0。它们为零。我也尝试过使用 default=>'0'
,但没有成功。知道为什么会发生这种情况吗? (Rails 3.0.3)
编辑添加:当我创建一个新用户时,它工作正常,并且一切看起来都正确。只是老用户在表中该值仍然为零。
I am currently trying to run this migration:
class AddDroppedProjectsCountToUser < ActiveRecord::Migration
def self.up
add_column :users, :dropped_projects, :integer, {:default=>0, :required=>true}
end
def self.down
remove_column :users, :dropped_projects
end
end
The column is added correctly, but none of the old records are populated with 0. They are nil. I have tried using default=>'0'
as well, to no avail. Any idea why this might be happening? (Rails 3.0.3)
Edited to add: When I create a new user it works fine, and everything looks correct. It's just the old users that still have nil for that value in the table.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你说:
相反,会发生什么?如果没有
:null=>false
,您仍然允许在dropped_projects
中使用NULL
,因此 PostgreSQL 没有理由将它们设置为 0。另外,我不认为:required
是add_column
;由于选项只是一个简单的Hash
并且add_column
仅查找它知道的选项,因此您的杂散:required
选项将被默默地忽略。What happens if you say:
instead? Without the
:null=>false
you're still allowingNULL
indropped_projects
so there's no reason for PostgreSQL to make them 0. Also, I don't think:required
is a valid option foradd_column
; since the options are just a simpleHash
andadd_column
only looks for options it knows about, your stray:required
option is silently ignored.你可以这样做:(
取自 http://apidock.com/rails/ActiveRecord/Migration )
you could do this:
(taken from http://apidock.com/rails/ActiveRecord/Migration)
我相信这是因为您正在更改旧的迁移,而不是创建新的迁移。
在这种情况下,解决方案是检查架构文件 (schema.rb)。它不会自动改变,并添加
I believe this is due to the fact that you are changing the old migration, instead of creating a new.
In this case, the solution is to check the schema file (schema.rb). It does not change automatically, and add