class PrincipalActivity < ActiveRecord::Base attr_accessible :principal_act_id, :principal_act_type, :principal_id, :user_id #虚拟关联 belongs_to :principal_act ,:polymorphic => true belongs_to :user validates :user_id,presence: true validates :principal_id,presence: true validates :principal_act_id,presence: true validates :principal_act_type, presence: true has_many :user_acts, :class_name => 'UserAcivity',:as =>:act after_save :add_user_activity before_destroy :destroy_user_activity #在个人动态里面增加当前动态 def add_user_activity user_activity = UserActivity.where("act_type = '#{self.principal_act_type.to_s}' and act_id = '#{self.principal_act_id}'").first if user_activity user_activity.save else user_activity = UserActivity.new user_activity.act_id = self.principal_act_id user_activity.act_type = self.principal_act_type user_activity.container_type = "Principal" user_activity.container_id = self.principal_id user_activity.user_id = self.user_id user_activity.save end end def destroy_user_activity user_activity = UserActivity.where("act_type = '#{self.forge_act_type.to_s}' and act_id = '#{self.forge_act_id}'") user_activity.destroy_all end end