From e733da728c1fac03e7eb562de7b1d3425d5e7aa9 Mon Sep 17 00:00:00 2001 From: Luka Murn Date: Tue, 15 Nov 2016 10:44:32 +0100 Subject: [PATCH] Fix a bug where user could be assigned to same project twice Closes SCI-675. --- app/models/user_organization.rb | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/app/models/user_organization.rb b/app/models/user_organization.rb index 2f283aa05..e964e6c91 100644 --- a/app/models/user_organization.rb +++ b/app/models/user_organization.rb @@ -29,15 +29,22 @@ class UserOrganization < ActiveRecord::Base # If any project of the organization has the sole owner and that # owner is the user to be removed from the organization, then we must # create a new owner of the project (the provided user). - organization.projects.each do |project| + organization.projects.find_each do |project| owners = project.user_projects.where(role: 0) if owners.count == 1 && owners.first.user == user - UserProject.create( - user: new_owner, - project: project, - role: 0, - assigned_by: user - ) + if project.users.exists?(new_owner.id) + # If the new owner is already assigned onto project, + # update its role + project.user_projects.find_by(user: new_owner).update(role: 0) + else + # Else, create a new association + UserProject.create( + user: new_owner, + project: project, + role: 0, + assigned_by: user + ) + end end end