# 批量将一个分类下的主题转换为群组私信

**URL:** <https://meta.discourse.org/t/bulk-convert-topics-from-a-category-to-group-pms/218811>\
**Category:** Product Support\
**Tags:** rails-console\
**Created:** [2022 年2 月 19 日 13:32 UTC](https://meta.discourse.org/t/bulk-convert-topics-from-a-category-to-group-pms/218811 "2022-02-19T13:32:31Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

作者： ![nathank](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/nathank/32/290039_2.png) [@nathank](https://meta.discourse.org/u/nathank)\
发布日期： [2025 年12 月 22 日 12:54 UTC](https://meta.discourse.org/t/bulk-convert-topics-from-a-category-to-group-pms/218811/4 "2025-12-22T12:54:21Z")

</div>

我后来（显然花了一段时间！）想出了两种实现此目的的方法。您可以通过用户界面（UI）进行操作，这对于小型分类（和小型群组）效果很好。在执行此操作时，需要小心避免触发不必要的通知，但这非常可行。

或者，如果您是自托管用户，可以使用 Rails 控制台，它更快、功能更强大。

## 从用户界面操作

1. 将群组中的其他成员从群组中移除（但保留用户名/电子邮件列表以便您轻松重新添加他们）。这将避免他们收到通知。
2. 遍历分类中的每个主题，使用管理员的扳手菜单将每个主题转换为私信（PM）。
  - 我发现最简单的方法是为每个主题打开一个单独的标签页，然后逐一处理它们。

3. 将群组添加到每个主题（现在是 PM）。
4. 将群组成员重新添加回群组。
5. 根据需要清理/删除每个群组消息中所有“小帖子”。

## 在 Rails 控制台中操作

通过进入容器然后调用控制台来访问控制台：

```plaintext
./launcher enter app
  rails c

```

设置分类和群组，然后将以下脚本复制到控制台中：

```rb
category_id = =CategoryID= 
group_name = '=GroupName='

group = Group.find_by('lower(name) = ?', group_name.downcase)
about_id = Category.find(category_id).topic_id

topic_ids = Topic.where(category_id: category_id).where.not(id: about_id).pluck(:id)

Topic.where(id: topic_ids).find_each do |topic|
  topic.archetype = Archetype.private_message
  topic.category_id = nil
  topic.subtype = 'user_to_user'
  topic.save!

  TopicAllowedGroup.find_or_create_by!(topic_id: topic.id, group_id: group.id)

  Post.where(topic_id: topic.id).pluck(:user_id).uniq.each do |uid|
    TopicAllowedUser.find_or_create_by!(topic_id: topic.id, user_id: uid)
  end
end

```

这完全不会通知用户，并且很好地保留了参与帖子的用户（以防他们不在群组中）。

---

_[View the full topic](https://meta.discourse.org/t/bulk-convert-topics-from-a-category-to-group-pms/218811)._
