Followable methods followers by Type

This commit is contained in:
ZengTao 2016-06-22 10:36:32 +08:00
parent 8197471328
commit e85edbf7c7
2 changed files with 27 additions and 1 deletions

View File

@ -1,5 +1,5 @@
module ActsAsFollowable
module Followable
module Followable #这个是被关注
def self.included(base)
base.extend ClassMethods
@ -8,12 +8,28 @@ module ActsAsFollowable
module ClassMethods
def acts_as_followable #This means can be followed - 被关注
include ActsAsFollowable::Followable::InstanceMethods
include ActsAsFollowable::FollowableExt
has_many :followers, as: :followable, dependent: :destroy, class_name: 'Follow'
end
end
module InstanceMethods
# 1: 查看某个 模型 关注我的所有对象
# 2: 查看某个 模型 的某个 实例 是否关注我了
def followers_count
self.followers.count
end
def followers(follower_type, options = {})
followers = follower_type.constantize.
joins(:follows).
where('follows.followable_id' => self.id,
'follows.followable_type' => class_name(self),
'follows.follower_type' => follower_type
)
return followers
end
end
end
end

View File

@ -0,0 +1,10 @@
module ActsAsFollowable
module FollowableExt #这个是被关注
private
# 有可能有STI的情况出现
def class_name(obj)
obj.class.superclass != ApplicationRecord ? obj.class.superclass.name : obj.class.name
end
end
end