D
D
dexdev2014-10-01 19:27:37
Ruby on Rails
dexdev, 2014-10-01 19:27:37

How to make a notification system for users?

In general, you need to make a notification system for users, notifications are shown directly on the site, in the header on any page, like you have added a comment, a new review, and so on. I can’t figure out how to implement this in any way ... Make a new Notifications model in it, register belongs_to user User has_many notifications
and how to architecture the base? notification_type notification_id I'm stumped! Put on the right path? Google doesn't help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanKiLL, 2014-10-02
@AdilA

There is a gem - https://github.com/pokonski/public_activity
Railscasts has a screencast on how to do it from scratch - railscasts.com/episodes/407-activity-feed-from-scratch but it shows notifications for everything and everyone.
I did this:
migration

class CreateActivities < ActiveRecord::Migration
  def change
    create_table :activities do |t|

      t.integer :user_id # кому нотификация
      t.integer :author_id # кто сделал действие
      t.string :action # какое действие например create значит что то создалось
      t.integer :trackable_id #полиморфизм
      t.string :trackable_type #полиморфизм
      t.boolean :read, default: false
      t.timestamps
    end

    add_index :activities, [:trackable_id, :trackable_type]
    add_index :activities, :user_id
    add_index :activities, :author_id
    add_index :activities, :read
  end
end

then in applicationController.rb there is such a method
def create_activity(to, author, action, trackable)
    activity = to.activities.build
    activity.author = author
    activity.action = action
    activity.trackable = trackable #полиморфизм обьект над которым произвелось действие
    activity.save
  end

and then in any controller,
for example, the user sends a message to another user or someone leaves a comment in general, any action
as a result, you then have such a tape like toaster.ru/my/tracker like a toaster
if you take all the notifications from the user
in the view you have everything, to whom the notification, the action that was taken and the object to which you can give a link
, for example like this, but this is a special case, of course you will have a friend
It will be written, for example
FanKiLL replied to the message title of the message
or
FanKiLL wrote a new post
In general, I suggest looking at the gem and the screencast that I gave at the beginning - and there this code will be more understandable - if you ask anything.
when a user enters a page with notifications, all unread messages are marked as read, and before that, you can display a list of unread messages wherever you want
current_user.activities.where(read: false).count

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question