How to truncate tables before seeding data?

Hey,

I started recently using seed.rb which I find really cool but there’s
something I haven’t figured out yet. Seeding is apparently for seeding
data but now I’m kinda playing around with it and it keeps adding data
so I have lots of duplicate data. Is there any command that truncates
every table on the database (like iterating over every model and
delete_all)?
Now I have to db:migrate:reset first in order to have clean tables.

Any suggestions?

I read your post this morning and thought, “WOW! Rails has defined an
approach for seeding data. That’s great! I’ll have to look into
that.” But I didn’t have an answer for you. Then later this morning,
I went looking for something I’d seen on Ryan B. excellent
Railscasts site (http://railscasts.com/) and found episode #179
staring me in the face. I highly recommend watching Ryan’s tutorial
on the subject, but I can give you the punchline:
#find_or_create_by_name(“blah”), or, alternatetively,
Mytable.delete_all.

–wpd

Hey,

thanks for the link. I’ll have a look at it later. Well I know of
Mytable.delete_all but I have like 40 tables already and find it a bit
annoying to write them down by hand. I’m looking for some function that
iterates through all my tables and truncates them.

Something like:
Blabla.allTablesOrModels.each do |t|
t.delete_all
end

If you want to delete all of the data in all of the tables, and you
are using sqlite3, you could just delete db/development.sqlite3 and
then either rerun your migrations, or execute “rake db:schema:load”.
If you are using MySQL, then you could probably use PHPMyAdmin or the
command line to delete the data. (You could use the command line to
delete the data in an Sqlite3 database as well.)

–wpd

ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.execute(“TRUNCATE #{table}”)
end

Hope this helps.

Thanks,
Abhinav

अभिनव
http://twitter.com/abhinav

On Tue, Sep 22, 2009 at 8:34 PM, Heinz S. <

Yes, but I want it to happen automatically so I think Abhinavs code
snippet is exactly what I was looking for. Thanks!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs