In a support discussion titled “Bulk delete users that match an email pattern,” fallais seeks to delete users whose emails match patterns like *.xyz or *.fun, noting they were imported from a spam-polluted phpBB forum and have no posts. christian_01 adds the need to also delete associated posts/topics. xrav3nz provides a Ruby solution using User.joins(:user_emails) with a LIKE query and recommends using UserDestroyer.new(Discourse.system_user).destroy(user, delete_posts: true) for safe, system-initiated deletion — cautioning that the action is irreversible and may impact performance if many users/posts are involved. fallais thanks xrav3nz and confirms intent to verify counts before deletion, noting a typo in the example (delete_posts: false → true). xrav3nz acknowledges the typo. The solution targets users with emails ending in specific domains, using SQL wildcards (%) and bulk iteration via find_each.
I would like to bulk delete users that match an email pattern such as :
*.xyz
*.fun
etc..
I tried this as of now : User.find(UserEmail.where("email like '%.fun'").pluck(:user_id)).count. But I can’t use the destroy_all function after a .where() …
This will have the system user delete the user and all of their posts.
To sum it up:
User.joins(:user_emails)
.where('lower(user_emails.email) LIKE ?', '%domain.com')
.find_each do |user|
UserDestroyer.new(Discourse.system_user).destroy(user, delete_posts: true)
end
Be ware that this is irreversable. You may want to verify the users selected by the query before actually deleting them. Also I am unsure of the performance implications if you’re deleting a great number of users and/or if they have a large number of posts.
Hi @xrav3nz ! This reply is awesome !
This is exactly what I need, I will try it right now, before I will confirm the amount with a basic count() of course as you suggested.
One remark, shouldn’t it be delete_post: true instead of false ?
My use case is very simple, I imported an old phpBB (thanks to @gerhard) and it has work perfectly, but this old forum what totally poluted by fake accounts.. They did not post any message. All email addresses looks like .fun or .xyz.