简体   繁体   English

Mongoid多态关联导轨

[英]Mongoid Polymorphic Association Rails

Work env: Rails 4.2 mongoid 5.1 工作环境:Rails 4.2 mongoid 5.1

Below are my models: 以下是我的模型:

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

We are trying to implement polymorphic functionality between Looks and Articles to Tags. 我们正在尝试在外观和标记商品之间实现多态功能。

ie Let's say we have a Tag named "politics", and we would like to add the tag to an Article with the score '0.9' and to a Look with the score '0.6'. 例如,假设我们有一个名为“ politics”的标签,我们希望将该标签添加到得分为“ 0.9”的文章中,并添加到得分为“ 0.6”的外观中。 The Score should be saved at the EntityTags Model. 分数应保存在EntityTags模型中。

The problem: The first assign of the tag works, but then when I try to assign the same tag to another entity, it removes it and reassigns it from the first one to the latter. 问题:标签的第一次分配有效,但是当我尝试将同一标签分配给另一个实体时,它将删除它,并将其从第一个重新分配给后者。

The assignment looks like the following: 分配如下所示:

entity.tags << tag

Does anybody know the proper way to save associations and create the EntityTag Object with the correct polymorphism and assignment properly? 有谁知道正确的方法来保存关联并创建具有正确多态性和分配的EntityTag对象?

Thanks! 谢谢!

根据此链接中的以下答案,我设法实现了一个非优雅的工作解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM