From fd132a8e82fed2f059b2dbbf5b30eca46cdc2005 Mon Sep 17 00:00:00 2001 From: Go MAEDA Date: Mon, 16 Oct 2023 15:03:08 +0000 Subject: Fix watcher handling on unsaved objects (#39186). Patch by Holger Just. git-svn-id: https://svn.redmine.org/redmine/trunk@22349 e93f8b46-1217-0410-a6f0-8f06a7374b81 --- .../acts_as_watchable/lib/acts_as_watchable.rb | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) (limited to 'lib') diff --git a/lib/plugins/acts_as_watchable/lib/acts_as_watchable.rb b/lib/plugins/acts_as_watchable/lib/acts_as_watchable.rb index 907535ec7..1a5888464 100644 --- a/lib/plugins/acts_as_watchable/lib/acts_as_watchable.rb +++ b/lib/plugins/acts_as_watchable/lib/acts_as_watchable.rb @@ -11,6 +11,7 @@ module Redmine module ClassMethods def acts_as_watchable(options = {}) return if self.included_modules.include?(Redmine::Acts::Watchable::InstanceMethods) + class_eval do has_many :watchers, :as => :watchable, :dependent => :delete_all has_many :watcher_users, :through => :watchers, :source => :user, :validate => false @@ -44,17 +45,26 @@ module Redmine # Adds user as a watcher def add_watcher(user) - # Rails does not reset the has_many :through association - watcher_users.reset - self.watchers << Watcher.new(:user => user) + if persisted? + # Rails does not reset the has_many :through association + watcher_users.reset + self.watchers << Watcher.new(:user => user) + else + self.watcher_users << user + end end # Removes user from the watchers list def remove_watcher(user) return nil unless user && (user.is_a?(User) || user.is_a?(Group)) - # Rails does not reset the has_many :through association - watcher_users.reset - watchers.where(:user_id => user.id).delete_all + + if persisted? + # Rails does not reset the has_many :through association + watcher_users.reset + watchers.where(:user_id => user.id).delete_all + else + watcher_users.delete(user) + end end # Adds/removes watcher -- cgit v1.2.3