如何将来自不同来源的通知分组到一个模型中

时间:2021-04-06 00:05:00

What I have right now is a Roleplay Model, and a Message Model.

我现在拥有的是角色扮演模型和消息模型。

I want them to share the same notification stream: They both should create a 'Notification' row which will then be displayed to the user. But I want the Notification also point to their parent. I thought about creating a parent_id and parent_class column so that I could get the parent object. But is there an already built in way of doing it?

我希望他们共享相同的通知流:他们都应该创建一个“通知”行,然后将其显示给用户。但我希望通知也指向他们的父母。我想创建一个parent_id和parent_class列,以便我可以获取父对象。但是,是否已经建立了这样做的方式?

I checked out Polymorphic Models, but I don't seem to really understand how to use it here.

我查看了Polymorphic Models,但我似乎并不真正理解如何在这里使用它。

1 个解决方案

#1


1  

The solution is exactly polymorphic models, if you add the parent_id and parent_class fields to the Notification model, you can easily create a polymorphic association at your notification model to implement it, here's how it would look:

解决方案就是多态模型,如果将parent_id和parent_class字段添加到Notification模型,您可以在通知模型中轻松创建多态关联来实现它,这里是它的外观:

class Notification < ActiveRecord::Base
  belongs_to :parent, :polymorphic => true
end

Then to use it it's quite simple:

然后使用它很简单:

message = # assign the message here
notification = Notification.create(:parent => message)

Then you can just query the notifications and use it to be your source of all notifications.

然后,您只需查询通知并将其用作所有通知的来源。

#1


1  

The solution is exactly polymorphic models, if you add the parent_id and parent_class fields to the Notification model, you can easily create a polymorphic association at your notification model to implement it, here's how it would look:

解决方案就是多态模型,如果将parent_id和parent_class字段添加到Notification模型,您可以在通知模型中轻松创建多态关联来实现它,这里是它的外观:

class Notification < ActiveRecord::Base
  belongs_to :parent, :polymorphic => true
end

Then to use it it's quite simple:

然后使用它很简单:

message = # assign the message here
notification = Notification.create(:parent => message)

Then you can just query the notifications and use it to be your source of all notifications.

然后,您只需查询通知并将其用作所有通知的来源。