Adegbite kelvin
Adegbite kelvin

Reputation: 33

How to create notification for followers with "Notifications gem"

I'm trying to setup notifications for the followers of a particular user so that whenever the user they're following posts a chapter, all the user's followers will get notified. I'm using https://github.com/rails-engine/notifications.

I've implemented following relationships which is working well on my app from this tutorial https://www.devwalks.com/lets-build-instagram-with-ruby-on-rails-part-6-follow-all-the-people/

This is what I've done so far with the codes

user.rb

  has_many :books, dependent: :destroy
  has_many :chapters, dependent: :destroy
  has_many :reviews, dependent: :destroy
  has_many :genres
  has_many :ratings

chapter.rb

belongs_to :book
belongs_to :user

after_commit :create_notifications, on: :create

private

def create_notifications
   Notification.create do |notification|
      notification.notify_type = 'chapter'
      notification.actor = self.book.user
      notification.user = self.user.followers
      notification.target = self
      notification.second_target = self.book
    end
end

views/notifications/_chapter.html.erb

<div class=''>
  <%= link_to notification.actor.username, main_app.profile_path(notification.actor.username) %> published a new chapter to 
  <%= link_to notification.second_target.title, main_app.book_path(notification.second_target) %>
</div>

<div class=''>
  <% unless notification.target.blank? %>
    <%= link_to notification.target.title, main_app.book_chapter_path(notification.second_target, notification.target.id) %>
  <% end %>
</div>

book.rb

belongs_to :user
has_many :chapters, dependent: :destroy

When i targeted the notifications to myself, I was notified correctly but when I did those above i got the error:

User(#58266780) expected, got #<ActiveRecord::Associations::CollectionProxy [#<User id: 3, name: "Otunba Olusaga of Saganation", username: "saga", email: "[email protected]", created_at: "2019-03-26 11:59:16", updated_at: "2019-03-27 09:13:58", admin: false, bio: "">]> which is an instance of User::ActiveRecord_Associations_CollectionProxy(#58325780)

More research shows that I have to "map the followers (Or use a batch insert tool) to insert multiple notifications" which I don't know how to do.

Explanation with example codes related to this will be so helpful, thanks!

Upvotes: 0

Views: 360

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

I'm not sure you can do bulk insert in this case as I undertand the Notification gem needs each notification to be for a single user? Maybe do this...

def create_notifications
   self.user.followers.each do |follower|
     Notification.create(notify_type: 'chapter', actor: self.book.user,
                         user: follower, target: self, second_target: self.book)

   end
end

Upvotes: 1

Related Questions