From eee097a9f89674c13f55ff75d725f181a3e05eb8 Mon Sep 17 00:00:00 2001 From: Matchu Date: Sun, 6 Aug 2023 16:23:22 -0700 Subject: [PATCH] Sync AuthUser and User names Callbacks are handy for this! --- app/models/auth_user.rb | 18 +++++++++++++++++- app/models/user.rb | 9 +++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/app/models/auth_user.rb b/app/models/auth_user.rb index 47e0d29d..92c832e8 100644 --- a/app/models/auth_user.rb +++ b/app/models/auth_user.rb @@ -8,7 +8,23 @@ class AuthUser < AuthRecord validates :name, presence: true, uniqueness: {case_sensitive: false}, length: {maximum: 20} - after_create do + has_one :user, foreign_key: :remote_id, inverse_of: :auth_user + + # It's important to keep AuthUser and User in sync. When we create an AuthUser + # (e.g. through the registration process), we create a matching User, too. And + # when the AuthUser's name changes, we update User to match. + # + # TODO: Should we sync deletions too? We don't do deletions anywhere in app + # right now, so I'll hold off to avoid leaving dead code around. + after_create :create_user + after_update :sync_name_with_user, if: :saved_change_to_name? + + def create_user User.create(name: name, auth_server_id: 1, remote_id: id) end + + def sync_name_with_user + user.name = name + user.save! + end end \ No newline at end of file diff --git a/app/models/user.rb b/app/models/user.rb index 62ddb5e9..fd509243 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -3,6 +3,8 @@ class User < ApplicationRecord PreviewTopContributorsCount = 3 + belongs_to :auth_user, foreign_key: :remote_id, inverse_of: :user + has_many :closet_hangers has_many :closet_lists has_many :closeted_items, through: :closet_hangers, source: :item @@ -22,6 +24,13 @@ class User < ApplicationRecord scope :top_contributors, -> { order('points DESC').where('points > 0') } + after_update :sync_name_with_auth_user, if: :saved_change_to_name? + + def sync_name_with_auth_user + auth_user.name = name + auth_user.save! + end + def admin? name == 'matchu' # you know that's right. end