【发布时间】:2017-03-20 10:03:41
【问题描述】:
工作环境:Rails 4.2 mongoid 5.1
以下是我的模型:
class Tag
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
belongs_to :entity_tags, :polymorphic => true
end
class EntityTag
include Mongoid::Document
include Mongoid::Timestamps
field :tag_id, type: String
field :entity_id, type: String // Entity could be Look or Article
field :entity_type, type: String // Entity could be Look or Article
field :score, type: Float
end
class Look
include Mongoid::Document
include Mongoid::Timestamps
has_many :tags, :as => :entity_tags
end
class Article
include Mongoid::Document
include Mongoid::Timestamps
has_many :tags, :as => :entity_tags
end
我们正在尝试在 Looks 和 Articles to Tags 之间实现多态功能。
即假设我们有一个名为“politics”的标签,我们想将该标签添加到得分为“0.9”的文章和得分为“0.6”的 Look。分数应保存在 EntityTags 模型中。
问题: 标签的第一个分配有效,但是当我尝试将相同的标签分配给另一个实体时,它会删除它并将其从第一个分配给后者。
作业如下所示:
entity.tags << tag
有人知道保存关联和创建具有正确多态性和正确分配的 EntityTag 对象的正确方法吗?
谢谢!
【问题讨论】:
标签: ruby-on-rails ruby mongodb mongoid polymorphic-associations