diff --git a/app/models/relationship.rb b/app/models/relationship.rb index 7b6790f8..2142276f 100644 --- a/app/models/relationship.rb +++ b/app/models/relationship.rb @@ -4,6 +4,22 @@ class Relationship < ActiveRecord::Base validates :source_id, presence: true validates :target_id, presence: true + after_create do + Notification.notify target, self + + # increment counts + source.increment! :friend_count + target.increment! :follower_count + end + + before_destroy do + Notification.denotify target, self + + # decrement counts + source.decrement! :friend_count + target.decrement! :follower_count + end + def notification_type(*_args) Notifications::StartedFollowing end diff --git a/app/models/user.rb b/app/models/user.rb index c27d516f..d0e30692 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -43,6 +43,12 @@ class User < ActiveRecord::Base end unless website.blank? end + before_destroy do + friends.each do |u| + unfollow u + end + end + def login=(login) @login = login end @@ -67,22 +73,12 @@ class User < ActiveRecord::Base # follows an user. def follow(target_user) - relationship = active_relationships.create(target: target_user) - Notification.notify target_user, relationship - - # increment counts - increment! :friend_count - target_user.increment! :follower_count + active_relationships.create(target: target_user) end # unfollows an user def unfollow(target_user) - relationship = active_relationships.find_by(target: target_user).destroy - Notification.denotify target_user, relationship - - # decrement counts - decrement! :friend_count - target_user.decrement! :follower_count + active_relationships.find_by(target: target_user).destroy end # @return [Boolean] true if +self+ is following +target_user+