From 024032faffb7ab0893413789f6cce2f22b73243d Mon Sep 17 00:00:00 2001 From: zmagod Date: Fri, 6 Apr 2018 15:41:50 +0200 Subject: [PATCH] refactor update protocol keywords action [fixes SCI-2257] --- app/models/protocol.rb | 8 +------- lib/tasks/protocol_keyword_team.rake | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) create mode 100644 lib/tasks/protocol_keyword_team.rake diff --git a/app/models/protocol.rb b/app/models/protocol.rb index b1814a3fb..e443ea1b7 100644 --- a/app/models/protocol.rb +++ b/app/models/protocol.rb @@ -499,13 +499,7 @@ class Protocol < ApplicationRecord self.protocol_protocol_keywords.destroy_all if keywords.present? keywords.each do |kw_name| - kw = ProtocolKeyword.find_by(name: kw_name) - if kw.blank? - kw = ProtocolKeyword.create( - name: kw_name, - team: self.team - ) - end + kw = ProtocolKeyword.find_or_create_by(name: kw_name, team: team) self.protocol_keywords << kw end end diff --git a/lib/tasks/protocol_keyword_team.rake b/lib/tasks/protocol_keyword_team.rake new file mode 100644 index 000000000..07f0d31f0 --- /dev/null +++ b/lib/tasks/protocol_keyword_team.rake @@ -0,0 +1,25 @@ +namespace :protocol_keyword_team do + desc 'Fixes false team_id on protocol keyword entry [bug SCI-2257]' + task exec: :environment do + puts '[sciNote] Start processing...' + Protocol.find_each do |protocol| + new_keywords = [] + protocol.protocol_keywords.find_each do |protocol_keyword| + next if protocol.team_id == protocol_keyword.team_id + # remove protocol keyword from protocol + ProtocolProtocolKeyword.where( + protocol_id: protocol.id, + protocol_keyword_id: protocol_keyword.id + ).destroy_all + # create new keyword with correct team + new_keywords << ProtocolKeyword.create( + name: protocol_keyword.name, + team_id: protocol.team_id + ) + end + # append newly created keywords to protocol + protocol.protocol_keywords << new_keywords + end + puts '[sciNote] Done!' + end +end