4

I can't find any conclusive articles showing how to create notifications in rails. Everyone seems to talk about Mailboxer like it's a good solution, but other than the one paragraph they have on the :Notify method, it seems very vague.

So I'm thinking of creating a notification model which belongs to Activity (Public Activity Gem) and then using an after_create callback on the activity model to call a notify method which then calls the notify method of the activities object in question.

As a diagram

    class Comment
    include PublicActivity::Model
      tracked

    def notify
          #Loop through all involved users of this modal instance and create a Notify record pointing to the public activity
        end
    end

    class Activity < PublicActivity::Activity # (I presume I can override the gems Activity model in my App?)
    after_create :notify

      private
        def notify
          #Call the notify function from the model referenced in the activity, in this case, comment
        end
    end

So when the comment modal is called, public activity tracks it which then calls back the comments notify method to save in a Notify model

Notify model would simply consist of

user_id, activity_id, read:boolean 

Note: I am trying my best to keep everything out of the controller, as I think the whole thing would be better handled in the model. But I'm open to suggestions

Thanks

David Sigley
  • 1,126
  • 2
  • 13
  • 28

1 Answers1

0

First you need to create a Notification model with required fields. And if you want to notify an admin every time a user has done any Activity(a new entry in Activity Model), you can create the notification in the after_create method on the Activity model.

class Activity
  after_create :notify

  def notify
    n = Notification.create(user_id: self.user_id, activity_id: self.id)
    n.save
  end
end

The above code will create an entry in the notification table for new Activity creation, with the activity id and the user id.

More explanation here.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Elmiya Agnes
  • 243
  • 2
  • 11