How to create notifications for this custom following relationships.
opened this issue · comments
Deleted user commented
Hi! I created a following relationship on my app and I'm trying to create notifications for the current_user whenever followed by another user.
I've tried to implement but notifications are not creating. It seems to be different for other types I've created.
user.rb
has_many :follower_relationships, foreign_key: :following_id, class_name: 'Follow'
has_many :followers, through: :follower_relationships, source: :follower
has_many :following_relationships, foreign_key: :follower_id, class_name: 'Follow'
has_many :following, through: :following_relationships, source: :following
def follow(user_id)
following_relationships.create(following_id: user_id)
end
def unfollow(user_id)
following_relationships.find_by(following_id: user_id).destroy
end
relationships_controller
class RelationshipsController < ApplicationController
def follow_user
@user = User.find_by! username: params[:username]
if current_user.follow @user.id
respond_to do |format|
format.html { redirect_to root_path }
format.js
end
end
end
def unfollow_user
@user = User.find_by! username: params[:username]
if current_user.unfollow @user.id
respond_to do |format|
format.html { redirect_to root_path }
format.js
end
end
end
end
follow.rb
class Follow < ApplicationRecord
belongs_to :follower, foreign_key: 'follower_id', class_name: 'User'
belongs_to :following, foreign_key: 'following_id', class_name: 'User'
end
I've tried this with the codes below but it's not working
user.rb
after_commit :create_notifications, on: :follow
private
def create_notifications
self.user.following.each do |follower|
Notification.create(notify_type: 'new_follower', actor: self, user: user)
end
end
after_commit :create_notifications, on: :follow
private
and also this in notify.rb
# Auto generate with notifications gem.
class Notification < ActiveRecord::Base
include Notifications::Model
def self.notify_follow(user_id, follower_id)
opts = {
notify_type: "follow",
user_id: user_id,
actor_id: follower_id
}
return if Notification.where(opts).count > 0
Notification.create opts
end
end