简体   繁体   中英

Mongoid Polymorphic Association Rails

Work env: 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'. The Score should be saved at the EntityTags Model.

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?

Thanks!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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