diff --git a/app/models/user.rb b/app/models/user.rb index 9350fb95c..73c8d6c5d 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -418,10 +418,13 @@ class User < Principal def projects_by_role return @projects_by_role if @projects_by_role - @projects_by_role = Hash.new {|h,k| h[k]=[]} + @projects_by_role = Hash.new([]) memberships.each do |membership| - membership.roles.each do |role| - @projects_by_role[role] << membership.project if membership.project + if membership.project + membership.roles.each do |role| + @projects_by_role[role] = [] unless @projects_by_role.key?(role) + @projects_by_role[role] << membership.project + end end end @projects_by_role.each do |role, projects| diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb index 51a49de01..7b4dac725 100644 --- a/test/unit/user_test.rb +++ b/test/unit/user_test.rb @@ -744,6 +744,13 @@ class UserTest < ActiveSupport::TestCase assert_equal [2], user.projects_by_role[Role.find(2)].collect(&:id).sort end + def test_accessing_projects_by_role_with_no_projects_should_return_an_empty_array + user = User.find(2) + assert_equal [], user.projects_by_role[Role.find(3)] + # should not update the hash + assert_nil user.projects_by_role.values.detect(&:blank?) + end + def test_projects_by_role_for_user_with_no_role user = User.generate! assert_equal({}, user.projects_by_role)