Bulk remove users

I have imported my old data from phpBB3 which went smooth. But I made a mistake by not first cleaning up the old inactive users and still importing them. I now have around 4000 users with no posts I wish to remove.

What is the best way to bulk remove users?

If you really don’t care about these users, then I would do this

  1. make a backup (better safe than sorry)
  2. ssh into your server and type
cd /var/discourse
./launcher enter app
rails c
User.where(post_count: 0).destroy_all
「いいね!」 2

These instructions produce the following error:
[1] pry(main)> User.where(post_count: 0).destroy_all ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column users.post_count does not exist LINE 1: SELECT "users".* FROM "users" WHERE "users"."post_count" = 0 ^ : SELECT "users".* FROM "users" WHERE "users"."post_count" = 0 from /var/www/discourse/vendor/bundle/ruby/2.3.0/gems/rack-mini-profiler-0.10.1/lib/patches/db/pg.rb:90:in `exec'

This is not really documented I think but if it is please point me in the right direction?

「いいね!」 1

“post count” != “post_count” ??

My bad, the post_count property was moved to another table for optimization reasons.

Here’s the updated query

User.joins(:user_stat).where("user_stats.post_count = 0").destroy_all
「いいね!」 6

Thank you, the updated query works!

「いいね!」 3

One of my sites uses SSO and we’re looking to remove users that have never posted and haven’t been seen in a year (to avoid killing users who are just quiet). Is this query valid in the rails console?

User.joins(:user_stat).where("user_stats.post_count = 0 AND previous_visit_at <= '2016-05-20'::timestamp").destroy_all
「いいね!」 2

It looks good to me.

「いいね!」 1

私も同じ問題に直面していますが、最終的なインポートを行う前に削除する必要があるユーザーがいます。設定やテーマなど、インポート前に基本構成を整える作業を進めていたのですが、(多くの作業の末に)実は既に4000人のユーザーがインポートされた部分的なインポートに対してこの作業を行っていたことに気づきました。

うっかり設定変更を忘れた際に、ダイジェストメールなどが誤って送信されないよう、それらのユーザーを削除したいと考えています。

管理者ユーザーのみを残すように、そのクエリをどのように修正すればよいでしょうか?
アクティブなユーザーリストには約4000人、一時停止中のユーザーリストには約30人のユーザーがいます。

ご協力よろしくお願いいたします :slight_smile:

注:現在、ユーザーとその関連レコードをクリーンに削除するための特定のクラスがあります:UserDestroyer

そのため、以下のようにする代わりに:

以下のように行うべきです:

destroyer = UserDestroyer.new(Discourse.system_user)
User.joins(:user_stat).where("user_stats.post_count = 0").each { |u| destroyer.destroy(u) }
「いいね!」 4