我正在尝试在 Rails 中设置一个通知系统,以及 mongoid(但我不认为这是 mongoid 特定的)。
基本结构是这样的 - 每个通知都有一个通知程序(负责通知的人)和一个通知程序(接收通知的人)。当用户 A 对用户 B 的帖子发表评论时(例如在博客系统中),用户 A 成为通知者,用户 B 成为通知者。
用户.rb
# nothing in here
通知.rb
has_one :notifier, :class_name => "User"
belongs_to :notifiee, :class_name => "User"
但是,当我这样做时:
@notification = Notification.new
@notification.notifier = current_user
@notification.notifiee = User.first #Just for the sake of the example
@notification.save
我收到此错误:
问题:将 (n) 个用户添加到通知 #通知程序时,Mongoid 可以 不确定要设置的反向外键。尝试的密钥是 "notifiee_id"。摘要:将文档添加到关系时,Mongoid 尝试将新添加的文档链接到关系的基础 在内存中,以及设置外键以在数据库上链接它们 边。在这种情况下,Mongoid无法确定反向 外键是。解决方法:如果不需要反转,例如 belongs_to或has_and_belongs_to_many,请确保 :inverse_of => nil 在关系上设置。如果需要相反,很可能 反向无法从关系的名称中找出,而你 将需要明确地告诉 Mongoid 关于关系的反向 是。
我可能做错了什么?或者,有没有更好的方法来建模?
任何帮助都非常感谢!谢谢。
您可能应该选择以下关联:
用户:
has_many :notifications_as_notifier, :class_name=>'Notification', :foreign_key=>'notifier_id'
has_many :notifications_as_notifiee, :class_name=>'Notification', :foreign_key=>'notifiee_id'
通知:
belongs_to :notifier, :class_name=>'User', :foreign_key=>'notifier_id'
belongs_to :notifiee, :class_name=>'User', :foreign_key=>'notifiee_id'
您的notifications
表应该有 notifier_id
和 notifiee_id
。
现在你可以做到了,
@notification = Notification.new
@notification.notifier = current_user
@notification.notifiee = User.first #Just for the sake of the example
@notification.save
我发现您的设置有问题的地方:
你有
has_one :notifier, :class_name => "User"
belongs_to :notifiee, :class_name => "User"
使用 has_on
时,其他关系(表)必须具有引用父关系的外键。在这里users
必须有一个列notification_id
什么的。这是不切实际的,因为单个用户有许多通知(基于你的解释)。
通过两个关系将通知关联到用户,但您提到了用于强制关联的外键的任何内容。
为什么在用户模型中没有反比关系?如果您可以访问以下内容:current_user.notifications_as_notifier
?,那会无济于事吗?