在 Rails 中撤消先前播种的数据 [英] Undo previously seeded data in Rails

查看:46
本文介绍了在 Rails 中撤消先前播种的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过编辑 db/seed.rb 文件并执行 rake db:seed 命令,我已将一行数据播种到我的表中.不知不觉中,我在该行中放入了一些错误的信息.所以我想删除之前添加的一行数据.是否有类似 rake db:rollback for rake db:migrate 的任何 rake 命令.

I have seeded a row of data to my table by editing db/seed.rb file and executing rake db:seed command. Unknowingly, I put some wrong information in to that row. So I want to remove the previously added row of data. Is there any rake command for the same like rake db:rollback for rake db:migrate.

推荐答案

这有几个方面:

1:当数据库中没有其他数据时,您想更改种子数据:

1: You want to change the seed data when no other data is present in the database:

您应该在更新seed.rb 文件后简单地重做rake db:seed.在尝试向该模型添加任何内容之前,请确保您拥有 MyModel.delete_all.

You should simply redo the rake db:seed after updating the seed.rb file. Make sure you have MyModel.delete_all before you try to add anything to that model.

2:您想更改种子数据,但数据库中还有其他数据

2: You want to change the seed data, but there are other data added to the database

这有点难.通常在这里做的最简单的事情是使用原始 sql 语句或使用诸如 PhpPpAdminPhpMyAdmin

This is a bit harder. Often the simplest thing to do here is to manually change the data with either raw sql-statements, or with the use of tools like PhpPpAdmin, PhpMyAdmin etc.

现在,有一种方法可以将其破解,那就是在 seed.rb 文件中做一些伏都教.所以你可以运行 rake db:seed deseed=true,然后在你的 seed.rb:

Now, there is possiby one way to hack this together, and that would be to do some voodoo in the seed.rb file. So you could run rake db:seed deseed=true, then in your seed.rb:

if ENV['deseed'] 
   #Do your deseeding action here
else
   #Do your seeding here.
end

你甚至可以变得非常疯狂并做这样的事情:

You could even get real crazy and do something like this:

deseed = ENV['desee']

#DANGER: Dirty hacks upcoming:
deseed? myModelCall = MyModel.method(:destroy_all): myModelCall = MyModel.method(:create)

myModelCall.call :user_id_or_whatevs => 23 #this creates or deletes a MyModel entity with the given parameters
#NOTE this might not work in all cases and I would not necessarily recommend doing this. 

#<3uby

这篇关于在 Rails 中撤消先前播种的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆