我可以通过哪些方式在 Rails 应用程序中实现通知? [英] What are some ways that I can implement notifications in a Rails application?

查看:46
本文介绍了我可以通过哪些方式在 Rails 应用程序中实现通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里想到的最简单的例子是 Facebook 通知,例如,当有人对您的状态发表评论、喜欢您的照片或只是向您发送某个游戏的邀请时.

有哪些方法可以在 Rails 应用程序中实现这一点,以便在用户阅读之前向用户显示通知,并且可能具有在不同平台上阅读的能力.

我不是在谈论使用服务器推送的类似实时聊天的通知,而是通过某种方式向用户展示自从他上次访问该网站以来发生的事情.>

例如,我阅读了一篇文章并发表了评论,然后有人回复了它.下次登录时,我希望能够看到有人回复了我的评论.

想到的一个解决方案是使用某种 Notification 模型,该模型具有 read 属性,当用户访问该站点时,它会显示当前未读的所有通知.

不使用关系数据库就没有更好的方法吗?

解决方案

我使用我现有的 User 模型,通过序列化的 messages 数组.>

通过迁移将 messages 列(TEXT 类型)添加到您的用户表中:

add_column :users, :messages, :text, :null =>假,:默认=>--- []"

然后在你的user模型中序列化它:

序列化:消息,数组

现在,您可以这样做:

# 添加消息@user.messages.push 你有一条新消息!"# 阅读消息@user.messages # =>[你有一条新消息!"]# 清除一条消息@user.messages.delete_at(0)# 清除所有消息@user.messages.clear# 获取消息计数@user.messages.empty?# =>真的@user.messages.count # =>0

如果您需要带有多个参数(发件人、主题、重要性)的更详细的消息,您始终可以使用哈希来代替.

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?

解决方案

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.

这篇关于我可以通过哪些方式在 Rails 应用程序中实现通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆