2011-11-01 92 views
3

我有以下迁移:Rails的迁移提供了错误

def self.up 
    add_column :project_statuses, :system_sequence, :integer, :default => 0, :null => false 

    ProjectStatus.create :name => 'Declined', :sequence => 35, :system_sequence => 110 

    ... 
end 

但是当我做了rake db:createrake db:migrate,我得到以下错误:

== NewProjectStatuses: migrating ============================================= 
-- add_column(:project_statuses, :system_sequence, :integer, {:default=>0, :null=>false}) 
    -> 0.0029s 
rake aborted! 
An error has occurred, this and all later migrations canceled: 

unknown attribute: system_sequence 
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1753:in `block in assign_attributes' 
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1747:in `each' 
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1747:in `assign_attributes' 
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1567:in `initialize' 
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:508:in `new' 
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:508:in `create' 
/[working dir]/db/migrate/20100816100139_new_project_statuses.rb:7:in `up' 

错误的行号是指Project.create :name => ...行。

看起来好像add_column行完全不运行,即使输出表示它正在运行。

运行一个rake db:migrate再次贯穿迁移很好。

这是为什么?

回答

15

尝试拨ProjectStatus.reset_column_informationadd_column块。

Rails缓存列信息(包括哪些列存在),我相信你在这里打的是你正在创建一个列,但是这不会触发Rails在可用列列表上重置它的缓存。因此,您的以下行失败,因为它不认为列存在。

我不确定为什么缓存是这样设计的,但是这种事情是explicitly mentioned in the example code regarding the usereset_column_information。我认为这是一个很好的机会。

也就是说,我也普遍认同Michael Durrant,关于使用通过迁移填充数据库的值。首选的方法是将您的默认/种子数据添加到rake任务(可以在任意时间运行)或您的seeds.rb文件。这与迁移相反,迁移只在当前模式版本早于指定迁移时运行。

+0

是的,这正是问题所在。谢谢!我可能会将这些违规行移动到seeds.rb文件中,但是之后我需要重构迁移行,因为它需要这些创建行才能工作。 – zlog

+0

够酷。祝你好运。 – jefflunt