2010-09-29 39 views
5

是否有人知道如何做Mongoid中的多態關聯,這是關係有利但不是嵌入關聯。Mongoid關係多態性協會

舉例來說,這是我Assignment型號:

class Assignment 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    field :user 
    field :due_at, :type => Time 

    referenced_in :assignable, :inverse_of => :assignment 
end 

,可以有多個模型多態性關係:

class Project 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    field :name, :type => String 

    references_many :assignments 
end 

這將引發一個錯誤,未知常量轉讓。當我將reference更改爲embed時,這一切都按照Mongoid's documentation中記錄的方式工作,但我需要的是reference

謝謝!

回答

4

從Mongoid Google Group看起來這不支持。這是我找到的newest relevant post

無論如何,這不是很難手動實現。這是我稱之爲主題的多態鏈接。

實現關係的逆向部分可能會稍微複雜一些,尤其是因爲跨多個類需要相同的代碼。

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 
+2

所以我認爲它現在可能:http://groups.google.com/group/mongoid/browse_thread/thread/edd3df20142625c4/bc56350c4ba198bc?lnk=gst&q=polymorphic#bc56350c4ba198bc – Vojto 2011-05-31 21:12:12

20

回答一個古老的帖子,但有人可能會覺得它有用。

現在也有一個多態belongs_to

class Action                               
    include Mongoid::Document                            
    include Mongoid::Timestamps::Created                         

    field :action, type: Symbol 

    belongs_to :subject, :polymorphic => true                        
end 

class User                                
    include Mongoid::Document                            
    include Mongoid::Timestamps                           
    field :username, type: String 
    has_many :actions, :as => :subject 
end 

class Company                               
    include Mongoid::Document                            
    include Mongoid::Timestamps                           

    field :name, type: String                            

    has_many :actions, :as => :subject 
end 
1

的Rails 4+

這裏是你將如何實現多態關聯Mongoid對於可以同時屬於一個Post一個Comment模型和Event模型。

Comment型號:

class Comment 
    include Mongoid::Document 
    belongs_to :commentable, polymorphic: true 

    # ... 
end 

Post/Event型號:

class Post 
    include Mongoid::Document 
    has_many :comments, as: :commentable 

    # ... 
end 

使用的擔憂:

在Rails 4+,您可以使用關注格局和app/models/concerns創建一個名爲commentable新模塊:

module Commentable 
    extend ActiveSupport::Concern 

    included do 
    has_many :comments, as: :commentable 
    end 
end 

,只是include這個模塊在你的機型:

class Post 
    include Mongoid::Document 
    include Commentable 

    # ... 
end