What are some ways that I can implement notifications in a Rails application?

别说谁变了你拦得住时间么 提交于 2019-12-04 15:57:40

问题


The simplest example here to think of are Facebook notifications, for example when somebody posts a comment on your status, likes your photo, or just sends you an invite to some game.

What are some ways to implement this in a Rails application, so that the notification is displayed to the user only until he reads it, and possibly with the ability to read it on different platforms.

I'm not talking here about real-time-chat-like notifications using server push, but rather some way of showing the user what happened since the last time he visited the site.

For example, I read an article and I post a comment and then somebody replies to it. The next time I log in, I want to be able to see that somebody replied to my comment.

One solution that comes to mind is having some kind of Notification model, which would have a read attribute, and when a user comes to the site, it will display all notifications that are currently unread.

Isn't there a better way to do this without the use of a relational database?


回答1:


I use my existing User model for this, by way of a serialized messages array.

Add a messages column (TEXT type) to your user table, via migration:

add_column :users, :messages, :text, :null => false, :default => "--- []"

Then serialize it in your user model:

serialize :messages, Array

Now, you can do this:

# Add messages
@user.messages.push "You have a new message!"

# Read messages
@user.messages # => ["You have a new message!"]

# Clear one message
@user.messages.delete_at(0)

# Clear all messages
@user.messages.clear

# Get message counts
@user.messages.empty? # => true
@user.messages.count  # => 0

If you need more detailed messages with multiple parameters (from, subject, importance), you could always use a hash instead.




回答2:


I have an Alert model on my site. When something happens an alert gets added and other users see the alert when they login. Important is to have a dismiss field, so a user can dismiss an alert, so the user won't see the same alert over and over again. It also has an area field, so you can connect the alert to a certain part of the website and it has a detail_link field, to give the user a link he can click on to go to see what the alert is about.



来源:https://stackoverflow.com/questions/9197291/what-are-some-ways-that-i-can-implement-notifications-in-a-rails-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!