Mongoid关系多态协会 [英] Mongoid relational Polymorphic Association

查看:66
本文介绍了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关系多态协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆