Truncate table(s) with rails console

前端 未结 9 1337
北恋
北恋 2021-02-02 05:51

I have this testingdatabase which, by now, is stuffed with junk. Now I\'ve done a few Table.destroy_all commands in the rails console which deletes all records and dependencies

相关标签:
9条回答
  • 2021-02-02 06:10

    You could also do rake db:rollback STEP=3 RAILS_ENV=test

    where 3 represents the number of migrations that you have in db/migrate. In example: If I have in

    db/migrate
    20140121065542_create_users.rb
    20140121065710_create_profiles.rb
    20140121065757_create_articles.rb
    20140121065900_create_comments.rb
    20140121065929_create_categories.rb
    

    So I have 5 migrations in total to remove. If I do rake db:rollback STEP=5 RAILS_ENV=test all the tables will be drop from my TEST database and if I remove RAILS_ENV=test than all the ENVIRONNMENT (production, test, development) tables will be delete and it cleans also db/shema.rb file from it's migration datas.

    0 讨论(0)
  • 2021-02-02 06:10

    I used below code to truncate all tables

    ActiveRecord::Base.establish_connection
    ActiveRecord::Base.connection.tables.each do |table|
      next if table == 'schema_migrations'
    
      case ActiveRecord::Base.connection.adapter_name.downcase.to_sym
        when :mysql2 , :postgresql
          ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
          ActiveRecord::Base.connection.execute("TRUNCATE #{table} RESTART IDENTITY")
        when :sqlite
          ActiveRecord::Base.connection.execute("DELETE FROM #{table}")
      end
    end
    
    0 讨论(0)
  • 2021-02-02 06:15

    This worked for me - ActiveRecord::Base.connection.execute("TRUNCATE table_name")

    0 讨论(0)
  • 2021-02-02 06:20

    The accepted answer only works if you need to recreate the whole database.
    To drop a single table (with the callbacks) and to get the IDs to start from 1:

    Model.destroy_all # Only necessary if you want to trigger callbacks.
    ActiveRecord::Base.connection.execute("TRUNCATE #{table_name} RESTART IDENTITY")
    

    If you are using Sqlite, it does not support truncate so do the following:

    Model.destroy_all # Only necessary if you want to trigger callbacks.
    ActiveRecord::Base.connection.execute("Delete from #{table_name}")
    ActiveRecord::Base.connection.execute("DELETE FROM SQLITE_SEQUENCE WHERE name='#{table_name}'")
    
    0 讨论(0)
  • 2021-02-02 06:23

    Assuming you're using MySQL or Postgre and not SQlite3 (which doesn't support TRUNCATE), you could do the following:

    MyModel.connection_pool.with_connection { |c| c.truncate(MyModel.table_name) }
    

    Note that this would not invoke ActiveRecord callbacks.

    0 讨论(0)
  • 2021-02-02 06:27

    Simply rebuild the database on the next test run (this will happen automatically after dropping it).

    rake db:drop RAILS_ENV=test

    0 讨论(0)
提交回复
热议问题