Rake DB:MIGRATE 遇到未定义方法的错误



我接管了一个由其他人建立的网站。我现在正在尝试在本地主机上启动并运行它。但是,当我迁移时,看起来以前的开发人员将代码放入迁移中,这些代码可能依赖于已经存在的种子。迁移文件如下所示。

def up
  add_column :supplies, :color, :string
  Supply.where(:title => "Shipped").first.update(:color =>'#e20ce8')
end
def down
  remove_column :supplies, :color
end

当我运行 rake db:migrate 时,我在这个文件上遇到的错误是......

rake aborted!
StandardError: An error has occurred, this and all later migrations 
canceled:
undefined method `update' for nil:NilClass

我该怎么做才能解决这个问题?

rake db:schema:load呢? 我相信这会让你开始前进,然后允许你使用rake db:migrate前进。

可能发生

的情况是,可以播种supply模型的先前迁移未运行或表被截断。作为一种好的做法,我们不应该使用迁移来设定数据种子,而应该只是通过迁移来构建架构。

您有 2 个选项:

如何在迁移中拉取此代码和其他播种机并将它们放入seeds.rb并运行rake db:seed

#in seeds.rb
Supply.where(:title => "Shipped").first.update(:color =>'#e20ce8')

在更新迁移之前进行检查。

instance = Supply.where(:title => "Shipped").first
instance.update(color: '#e20ce8') if instance.present?

最新更新