如何在 Mongoid 中实现多对多关系?比如我们有一个User,它可以有很多个Notifications,而Notification是SpecificNotification的父类.每个用户都可以收到N 通知的提醒(即通知、特定通知)并且每个通知(再次表示两者)都可以应用于N 用户。
我尝试了以下方法:
在 user.rb 中:
class User
include Mongoid::Document
has_and_belongs_to_many :notifications
attr_accessible :notifications, :notification_ids
end
在notification.rb中:
class Notification
include Mongoid::Document
has_and_belongs_to_many :users
attr_accessible :users, :user_ids
end
在specificnotification.rb中:
class SpecificNotification < Notification
field :something_specific
end
但是当我创建一个SpecificNotification时,相关的Users不会更新——Users只会记录Notifications,而不是 SpecificNotifications。怎么了?
最佳答案
这不是您问题的直接答案,但这是我的 2 美分:
我建议考虑非规范化您的数据模型。在我所拥有的社交网络上,我遇到了一个非常相似的问题:用户有很多通知,而同样的通知会发送给很多用户。
但我没有建立多对多关系,而是采用了 noSQL 风格,将通知复制到每个用户。这样就可以更轻松地使用每个用户的姓名和其他属性自定义通知。我认为这将是使用 mongodb 对其建模的“正确方法”。
同样适用于这个特定字段,因为您使用的是 mongoid,某些对象可能有也可能没有某些字段。如果没有很多类型的通知和很多字段,也许最好将该字段放在 Notification 模型上。
关于ruby - 使用 Mongoid 实现多态多对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7959413/