# 通过 SSO 登录创建新用户时出现 Discourse DB 错误

**URL:** https://meta.discourse.org/t/discourse-db-error-when-creating-new-users-via-sso-login/127442
**Category:** Bug
**Created:** [2019年九月2日 22:14 UTC](https://meta.discourse.org/t/discourse-db-error-when-creating-new-users-via-sso-login/127442 "2019-09-02T22:14:41Z")
**Posts on this page:** 1
**Showing post:** 2

<div class="post-metadata">

### Author: ![sam](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/sam/32/102149_2.png) [@sam](https://meta.discourse.org/u/sam)
#### Post date: [2019年九月3日 04:35 UTC](https://meta.discourse.org/t/discourse-db-error-when-creating-new-users-via-sso-login/127442/2 "2019-09-03T04:35:22Z")

</div>

这与以下代码有关：

> <https://github.com/discourse/discourse/blob/b9954b53bbaf65d3c5ff6eb9a1f321a61408e768/app/models/user.rb#L1389-L1405>

这里发生的情况是，我们按如下方式修改了 category\_user 的索引：

> <https://github.com/discourse/discourse/blob/b9954b53bbaf65d3c5ff6eb9a1f321a61408e768/app/models/category_user.rb#L215-L216>

您的站点设置中是否存在一个 **同时** 被设置为“默认关注”和“默认追踪”的群组？

请查看：`default categories watching`、`default categories tracking`、`default categories muted` 以及 `default categories watching first post`。

以下修复可以解决问题：

```diff
diff --git a/app/models/user.rb b/app/models/user.rb
index c1a94949a6..85b2ca9244 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1390,10 +1390,15 @@ class User < ActiveRecord::Base
     return if self.staged?
 
     values = []
+ # 稍后分配集合
+ seen = nil
 
     %w{watching watching_first_post tracking muted}.each do |s|
       category_ids = SiteSetting.get("default_categories_#{s}").split("|").map(&:to_i)
       category_ids.each do |category_id|
+ seen ||= Set.new
+ next if seen.include?(category_id)
+ seen << category_id
         next if category_id == 0
         values << "(#{self.id}, #{category_id}, #{CategoryUser.notification_levels[s.to_sym]})"
       end
diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb
index cc50d88b2e..4075ee6194 100644
--- a/spec/models/user_spec.rb
+++ b/spec/models/user_spec.rb
@@ -1603,8 +1603,12 @@ describe User do
 
       SiteSetting.default_categories_watching = category0.id.to_s
       SiteSetting.default_categories_tracking = category1.id.to_s
- SiteSetting.default_categories_muted = category2.id.to_s
+
+ # 这是无效的，但我们不进行验证，因此确保不会导致任何故障
+ SiteSetting.default_categories_muted = "#{category2.id}|#{category0.id}"
+
       SiteSetting.default_categories_watching_first_post = category3.id.to_s
+
     end
 
     it "has overriden preferences" do

```

但我并不喜欢这个修复方案。站点设置应在保存时验证是否存在重叠，并且我们应该迁移掉错误的数据。

@Daniel 我认为你在这里引入了新的约束，也许可以在用户设置站点设置时跟进添加一个验证？

---

_[View the full topic](https://meta.discourse.org/t/discourse-db-error-when-creating-new-users-via-sso-login/127442)._
