Rails seed: how to trim a DB table?

Before visiting the test data in the DB table, I need to truncate the table (I need to reset the primary key), I try to do this as follows:

ActiveRecord::Base.connection.execute("TRUNCATE users")

but when I print the data from the database, I still do not see the primary key counting from 1.

What am I doing wrong?

EDIT:

In addition, I tried to manually start the PostgreSQL database in the terminal

truncate users

But the primary account does not start at 1.

DECISION:

In Postgres, run:

ALTER SEQUENCE users_id_seq RESTART WITH 1;
+5
source share
4 answers

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;.

: SQLite TRUNCATE,

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

, db postgres, - , db :

[
  MyModel1,
  MyModel2,
  MyModel3
].each do |m|
  ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{m.table_name} RESTART IDENTITY;")
end
+3

, , - . ( gem 'database_cleaner' Gemfile) GEM, , , schema._

, rake db:seed,

DatabaseCleaner.clean_with(:truncation)

. 1 .


: .

+3

From Rails to csv_upload.rb I used and worked.

ActiveRecord :: Base.connection.execute ('TRUNCATE model_name RESTART IDENTITY')

0
source

All Articles