class CourseActivity < ActiveRecord::Base attr_accessible :user_id, :course_act_id,:course_act_type,:course_id # 虚拟关联 belongs_to :course_act ,:polymorphic => true belongs_to :course belongs_to :user has_many :user_acts, :class_name => 'UserAcivity',:as =>:act after_save :add_user_activity, :add_course_activity before_destroy :destroy_user_activity, :destroy_org_activity #在个人动态里面增加当前动态 def add_user_activity user_activity = UserActivity.where("act_type = '#{self.course_act_type.to_s}' and act_id = '#{self.course_act_id}'").first if user_activity user_activity.save else if self.course_act_type == 'Message' && !self.course_act.parent_id.nil? user_activity = UserActivity.where("act_type = 'Message' and act_id = #{self.course_act.parent.id}").first user_activity.created_at = self.created_at user_activity.save else user_activity = UserActivity.new user_activity.act_id = self.course_act_id user_activity.act_type = self.course_act_type user_activity.container_type = "Course" user_activity.container_id = self.course_id user_activity.user_id = self.user_id user_activity.save end end end def add_course_activity org_activity = OrgActivity.where("org_act_type = '#{self.course_act_type.to_s}' and org_act_id = '#{self.course_act_id}'").first if org_activity org_activity.save else if self.course_act_type == 'Message' && !self.course_act.parent_id.nil? org_activity = OrgActivity.where("org_act_type = 'Message' and org_act_id = #{self.course_act.parent.id}").first org_activity.created_at = self.created_at org_activity.save else OrgActivity.create(:user_id => self.user_id, :org_act_id => self.course_act_id, :org_act_type => self.course_act_type, :container_id => self.course_id, :container_type => 'Course', :created_at => self.created_at, :updated_at => self.updated_at) end end end def destroy_user_activity user_activity = UserActivity.where("act_type = '#{self.course_act_type.to_s}' and act_id = '#{self.course_act_id}'") user_activity.destroy_all end def destroy_org_activity org_activity = OrgActivity.where("org_act_type = '#{self.course_act_type.to_s}' and org_act_id = '#{self.course_act_id}'") org_activity.destroy_all end end