Mongoid关系多态协会

编程入门 行业动态 更新时间:2024-10-10 18:27:49
本文介绍了Mongoid关系多态协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有人知道如何在Mongoid中进行多态关联,这对关系有利,但对嵌入不利.

Does anyone know how to do a polymorphic association in Mongoid that is of the relational favor but not the embedding one.

例如,这是我的Assignment模型:

class Assignment include Mongoid::Document include Mongoid::Timestamps field :user field :due_at, :type => Time referenced_in :assignable, :inverse_of => :assignment end

可以与多个模型具有多态关系:

that can have a polymorphic relationship with multiple models:

class Project include Mongoid::Document include Mongoid::Timestamps field :name, :type => String references_many :assignments end

这将引发错误,指出未知的常量可分配.当我将reference更改为embed时,所有操作均如 Mongoid的文档所述,但我需要它是reference.

This throws an error saying unknown constant Assignable. When I change the reference to embed, this all works as documented in Mongoid's documentation, but I need it to be reference.

谢谢!

推荐答案

从Mongoid Google网上论坛看来,它不受支持.这是最新的相关帖子我找到了.

From Mongoid Google Group it looks like this is not supported. Here's the newest relevant post I found.

无论如何,这并不难手动实现.这是我称为主题的多态链接.

Anyway, this is not to hard to implement manually. Here's my polymorphic link called Subject.

实现关系的逆部分可能会稍微复杂一些,特别是因为您将需要在多个类中使用相同的代码.

Implementing inverse part of relation might be somewhat more complicated, especially because you will need same code across multiple classes.

class Notification include Mongoid::Document include Mongoid::Timestamps field :type, :type => String field :subject_type, :type => String field :subject_id, :type => BSON::ObjectId referenced_in :sender, :class_name => "User", :inverse_of => :sent_notifications referenced_in :recipient, :class_name => "User", :inverse_of => :received_notifications def subject @subject ||= if subject_type && subject_id subject_type.constantize.find(subject_id) end end def subject=(subject) self.subject_type = subject.class.name self.subject_id = subject.id end end

更多推荐

Mongoid关系多态协会

本文发布于:2023-08-03 14:51:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1287781.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:关系   协会   多态   Mongoid

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!