class CourseGroup < ActiveRecord :: Base
# attr_accessible :title, :body
belongs_to :course , counter_cache : true
has_many :course_members
has_many :members
has_many :memberships , :class_name = > 'Member'
has_many :member_principals , :class_name = > 'Member' ,
:include = > :principal ,
:conditions = > " #{ Principal . table_name } .type='Group' OR ( #{ Principal . table_name } .type='User' AND #{ Principal . table_name } .status= #{ Principal :: STATUS_ACTIVE } ) "
has_many :principals , :through = > :member_principals , :source = > :principal
has_many :users , :through = > :members
has_many :homework_group_settings , :dependent = > :destroy
has_many :exercise_group_settings , :dependent = > :destroy
has_many :homework_group_reviews , :dependent = > :destroy
has_many :poll_group_settings , :dependent = > :destroy
has_many :attachment_group_settings , :dependent = > :destroy
has_many :teacher_course_groups , :dependent = > :destroy
before_destroy :set_member_nil
# attr_accessible :name
validates :name , :presence = > true , :length = > { :maximum = > 20 } , :uniqueness = > { :scope = > :course_id }
after_create :generate_invite_code
# 延迟生成邀请码
def invite_code
return generate_invite_code
end
# 生成邀请码
CODES = %W( 2 3 4 5 6 7 8 9 A B C D E F G H J K L N M O P Q R S T U V W X Y Z )
def generate_invite_code
code = read_attribute ( :invite_code )
if ! code || code . size < 6
code = CODES . sample ( 6 ) . join
return generate_invite_code if CourseGroup . where ( invite_code : code ) . present?
update_attribute ( :invite_code , code )
end
code
end
def set_member_nil
if self . members && self . members . count > 0
self . members . update_all ( " course_group_id = 0 " )
end
end
end