ruby - How to clear database before seeding in rails -


is there simple line of code can include @ top of seed file clear out each table before inserting new seed data without running rake commands rollback tables or databases?

i thinking like:

[foo, bar].each{|class| class.destroy_all} 

the point want add new data each new insertion starts id: 1. want avoid deleting table 100 rows , when add new data it's starting 101.

updated answer

you've install (or can add gem 'database_cleaner' gemfile) gem called database cleaner helps clean database without affecting database schema._

clean database each time whenever rake db:seed paste

# updated require 'database_cleaner'  databasecleaner.clean_with(:truncation) 

on top of seed file. it'll clear database , start count 1 again.


disclaimer : updated answer tested, , working in system.



===========================================================================

previous untested answer

ya can it's depends on database you're using.

below i'm giving solution popular dbs.

in mysql, truncate table; deletes rows , resets auto increment counter.

in postgresql, it not automatically. can use truncate table table restart identity;.

in sqlite, there no truncate statement, instead, it's

delete table; delete sqlite_sequence name='table'; 


you can try this

activerecord::base.connection.tables.each |table|   activerecord::base.connection.execute("truncate #{table}") end 


you can select 1 of solution & implement seed file.

i hope you... ;)


disclaimer : i've share knowledge purpose of help, solution didn't tested.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -