ruby-on-railsrubydatabasesqlitesqlite3-ruby

How to clear database before seeding in rails


Is there a simple line of code I can include at the top of my seed file to clear out each table before inserting new seed data without running any rake commands to rollback tables or databases?

I was thinking something like:

[Foo, Bar].each{|class| class.destroy_all}

The point is I want to add new data where each new insertion starts from id: 1. What I want to avoid is deleting a table with 100 rows and when I add new data it's starting from 101.


Solution

  • Updated Answer

    You've to install (OR you can add gem 'database_cleaner' to your Gemfile) a GEM called Database Cleaner which helps to clean your database without affecting your database schema._

    To clean your database each time whenever you do rake db:seed then paste

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

    on the top of your seed file. It'll clear your database and start count from 1 again.


    Disclaimer : This updated answer is tested, and working perfectly in my system.



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

    Previous Untested Answer

    Ya you can do that but it's depends on which database you're using.

    Below I'm giving solution for some popular DBs.

    In MySQL, TRUNCATE table; deletes all rows and resets the auto increment counter.

    In PostgreSQL, it does not do this automatically. You can use TRUNCATE TABLE table RESTART IDENTITY;.

    In SQLite, there is no TRUNCATE statement, instead, it's

    DELETE FROM table;
    DELETE FROM sqlite_sequence WHERE name='table';
    


    You can also try this

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


    You can select any one of the solution & implement it to your seed file.

    I hope this will help you... ;)


    Disclaimer : I've share my knowledge for the purpose of your help, but this solution was didn't tested.