2010-09-29 74 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