有没有人知道如何进行多态关联,Mongoid这是关系优势,而不是嵌入关联.
例如,这是我的Assignment模型:
class Assignment
include Mongoid::Document
include Mongoid::Timestamps
field :user
field :due_at, :type => Time
referenced_in :assignable, :inverse_of => :assignment
end
Run Code Online (Sandbox Code Playgroud)
可以与多个模型建立多态关系:
class Project
include Mongoid::Document
include Mongoid::Timestamps
field :name, :type => String
references_many :assignments
end
Run Code Online (Sandbox Code Playgroud)
这会抛出一个错误,指出未知的常量Assignable.当我改变referenceto时embed,这一切都按照Mongoid的文档记录,但我需要它reference.
谢谢!
Kim*_*hto 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
Run Code Online (Sandbox Code Playgroud)
从 Mongoid Google Group 来看,这似乎不受支持。这是我找到的最新相关帖子。
无论如何,这并不难手动实现。这是我的多态链接,称为“主题”。
实现关系的逆部分可能会更复杂一些,特别是因为您需要跨多个类使用相同的代码。
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5715 次 |
| 最近记录: |