after_create and before_destroy

This commit is contained in:
nilsding 2014-12-28 21:40:33 +01:00
parent fec91eeb5b
commit 9c9c4fdc5d
2 changed files with 24 additions and 12 deletions

View File

@ -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

View File

@ -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+