diff --git a/app/models/course/group_user.rb b/app/models/course/group_user.rb index ef96e8653b6..22152eceaa0 100644 --- a/app/models/course/group_user.rb +++ b/app/models/course/group_user.rb @@ -5,6 +5,8 @@ class Course::GroupUser < ActiveRecord::Base enum role: { normal: 0, manager: 1 } + validate :user_and_group_in_same_course + belongs_to :user, inverse_of: :course_group_users belongs_to :course_group, class_name: Course::Group.name, inverse_of: :group_users @@ -16,4 +18,9 @@ class Course::GroupUser < ActiveRecord::Base def set_defaults self.role ||= :normal end + + def user_and_group_in_same_course #:nodoc: + return if user.courses.include?(group.course) + errors.add(:user, I18n.t('activerecord.errors.models.course_group_user.not_enrolled')) + end end diff --git a/config/locales/en/activerecord/errors/models/course_group_user.yml b/config/locales/en/activerecord/errors/models/course_group_user.yml new file mode 100644 index 00000000000..bb197a93629 --- /dev/null +++ b/config/locales/en/activerecord/errors/models/course_group_user.yml @@ -0,0 +1,6 @@ +en: + activerecord: + errors: + models: + course_group_user: + not_enrolled: 'user must be enrolled in same course as group' diff --git a/spec/factories/course_group_users.rb b/spec/factories/course_group_users.rb index 420893603bd..b2d0b654953 100644 --- a/spec/factories/course_group_users.rb +++ b/spec/factories/course_group_users.rb @@ -6,6 +6,12 @@ creator updater + after(:build) do |group_user| + course = group_user.group.course + user = group_user.user + create(:course_user, course: course, user: user) unless user.courses.include?(course) + end + factory :course_group_student factory :course_group_manager do role :manager diff --git a/spec/models/course/group_user_spec.rb b/spec/models/course/group_user_spec.rb index 9db585f1edd..1bc289770cf 100644 --- a/spec/models/course/group_user_spec.rb +++ b/spec/models/course/group_user_spec.rb @@ -3,4 +3,14 @@ RSpec.describe Course::GroupUser, type: :model do it { is_expected.to belong_to(:user).inverse_of(:course_group_users) } it { is_expected.to belong_to(:course_group).inverse_of(:group_users) } + + let!(:instance) { create(:instance) } + with_tenant(:instance) do + subject { build(:course_group_user) } + + context 'when user is not enrolled in group\'s course' do + before { subject.user.course_users.delete_all } + it { is_expected.not_to be_valid } + end + end end