Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undo previously seeded data in Rails

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.

like image 921
Rajesh Omanakuttan Avatar asked Feb 19 '13 10:02

Rajesh Omanakuttan


People also ask

How do you remove seed rails?

To undo a rails generate command, run a rails destroy command. You can then edit the file and run rake db:migrate again.

Which command is used to rollback migration in Rails?

You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.

What does Rails DB Reset do?

db:reset: Resets your database using your migrations for the current environment. It does this by running the db:drop , db:create , db:migrate tasks. db:rollback: Rolls the schema back to the previous version, undoing the migration that you just ran.

What is seed RB in rails?

Rails seed files are a useful way of populating a database with the initial data needed for a Rails project. The Rails db/seeds. rb file contains plain Ruby code and can be run with the Rails-default rails db:seed task.


1 Answers

There are a couple of aspects to this:

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

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: You want to change the seed data, but there are other data added to the database

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.


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
like image 156
Automatico Avatar answered Oct 12 '22 05:10

Automatico