class CourseMessage < ActiveRecord::Base
  # status说明： status在课程不同的类型，区分不同的功能
  # HomeworkCommon：status：
  # nil：发布了作业； 1：作业截止时间到了提醒！；2:开启匿评； 3：关闭匿评； 4：匿评开始失败
  attr_accessible :course_id, :course_message_id, :course_message_type, :user_id, :viewed, :content, :status

  # 多态 虚拟关联
  belongs_to :course_message ,:polymorphic => true
  belongs_to :course
  belongs_to :user
  has_many :message_alls, :class_name => 'MessageAll',:as =>:message,  :dependent => :destroy

  validates :user_id,presence: true
  validates :course_id,presence: true
  validates :course_message_id,presence: true
  validates :course_message_type, presence: true
  validates_length_of :content, :maximum => 100
  after_create :add_user_message

  def add_user_message
    if MessageAll.where("message_type = '#{self.class.to_s}' and message_id = '#{self.id}'").first.nil?
      self.message_alls << MessageAll.new(:user_id => self.user_id)
    end
  end
end
