我找不到任何显示如何在rails中创建通知的结论性文章。每个人似乎都在谈论Mailboxer,因为它是一个很好的解决方案,但除了他们对:Notify方法的一个段落之外,它似乎很模糊。
所以我正在考虑创建属于Activity(公共活动Gem)的通知模型,然后在活动模型上使用after_create回调来调用notify方法,然后该方法调用相关活动对象的notify方法。
作为图表
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
因此,当调用注释模式时,公共活动会跟踪它,然后回调注释通知方法以保存在通知模型中
通知模型只包含
user_id, activity_id, read:boolean
注意:我正在尽力将所有内容都保留在控制器之外,因为我认为在模型中可以更好地处理整个事情。但我愿意接受建议
由于
答案 0 :(得分:0)
首先,您需要创建包含必填字段的通知模型。如果您想在每次用户完成任何活动(活动模型中的新条目)时通知管理员,您可以在活动模型的after_create方法中创建通知。
class Activity
after_create :notify
def notify
n = Notification.create(user_id: self.user_id, activity_id: self.id)
n.save
end
end
上面的代码将在通知表中为新的Activity创建创建一个条目,其中包含活动ID和用户ID。
更多解释here。