From 64eb1fbf8849b6e4bfc50de11ee9a3b93ba1f777 Mon Sep 17 00:00:00 2001 From: WANG QIANG Date: Sat, 16 May 2015 15:57:51 +0800 Subject: [PATCH] Validate user add to the group are in the same course with group --- app/models/course/group_user.rb | 9 +++++++++ config/locales/en.yml | 7 +++++++ spec/factories/course_group_users.rb | 6 ++++++ spec/models/course/group_user_spec.rb | 10 ++++++++++ 4 files changed, 32 insertions(+) diff --git a/app/models/course/group_user.rb b/app/models/course/group_user.rb index b7ad61aada1..935af4ebfee 100644 --- a/app/models/course/group_user.rb +++ b/app/models/course/group_user.rb @@ -4,5 +4,14 @@ class Course::GroupUser < ActiveRecord::Base belongs_to :group, class_name: Course::Group.name, inverse_of: :group_users, foreign_key: :course_group_id + validate :user_and_group_in_same_course + enum role: { normal: 0, manager: 1 } + + private + + def user_and_group_in_same_course #:nodoc: + return if user.courses.include?(group.course) + errors.add(:user, I18n.translate('activerecord.errors.models.course_group_user.not_enrolled')) + end end diff --git a/config/locales/en.yml b/config/locales/en.yml index 678934e0df3..7de891871b3 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -24,6 +24,13 @@ en: 'yes': 'Yes' 'no': 'No' delete: 'Delete' + + activerecord: + errors: + models: + course_group_user: + not_enrolled: 'user must be enrolled in same course as group' + layout: coursemology: 'Coursemology' navbar: diff --git a/spec/factories/course_group_users.rb b/spec/factories/course_group_users.rb index 54706195ff9..f579cb5fff9 100644 --- a/spec/factories/course_group_users.rb +++ b/spec/factories/course_group_users.rb @@ -6,6 +6,12 @@ association :group, factory: :course_group role :normal + 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, parent: :course_group_user factory :course_group_manager, parent: :course_group_user do role :manager diff --git a/spec/models/course/group_user_spec.rb b/spec/models/course/group_user_spec.rb index fff3986279b..52d28b79aba 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(: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