【问题标题】:rake db:migrate runs into an error for an undefined methodrake db:migrate 遇到未定义方法的错误
【发布时间】:2018-04-11 18:52:48
【问题描述】:

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

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

我能做些什么来解决这个问题?

【问题讨论】:

  • 尝试update_attributes 而不是update
  • 感激不尽。它有效,是一个简单而优雅的解决方案。
  • np,我会把它作为答案提交

标签: ruby postgresql rake database-migration


【解决方案1】:

可能发生的情况是之前的可以为 supply 模型播种的迁移未运行或表被截断。作为一种好的做法,我们不应该使用迁移来播种数据,而应该使用迁移来构建模式。

你有两个选择:

如何在迁移中提取此代码和其他播种机并将它们放入 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?

【讨论】:

    【解决方案2】:

    rake db:schema:load 怎么样?我相信这会让你继续前进,然后让你继续使用rake db:migrate

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 2012-06-30
      相关资源
      最近更新 更多