rake db:migrate 遇到未定义方法的错误
rake db:migrate runs into an error for an undefined method
我接手了一个别人建的网站。我现在正在尝试在本地主机上启动并 运行ning。但是,当我迁移时,看起来以前的开发人员将代码放入可能依赖于已经存在的种子的迁移中。迁移文件如下所示。
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
我该怎么做才能解决这个问题?
可能发生的情况是,之前可以为 supply
模型播种的迁移不是 运行 或 table 被截断了。作为一种好的做法,我们不应该使用迁移来播种数据,而应该只使用迁移来构建模式。
您有 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?
rake db:schema:load
怎么样?我相信这会让你继续前进,然后让你继续使用 rake db:migrate
。
我接手了一个别人建的网站。我现在正在尝试在本地主机上启动并 运行ning。但是,当我迁移时,看起来以前的开发人员将代码放入可能依赖于已经存在的种子的迁移中。迁移文件如下所示。
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
我该怎么做才能解决这个问题?
可能发生的情况是,之前可以为 supply
模型播种的迁移不是 运行 或 table 被截断了。作为一种好的做法,我们不应该使用迁移来播种数据,而应该只使用迁移来构建模式。
您有 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?
rake db:schema:load
怎么样?我相信这会让你继续前进,然后让你继续使用 rake db:migrate
。