Mongoid relational Polymorphic Association

后端 未结 3 1808
南旧
南旧 2021-02-10 06:14

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

For instance this is my Ass

3条回答
  •  情书的邮戳
    2021-02-10 06:46

    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
    

提交回复
热议问题