【问题标题】:Mongoid Polymorphic Association RailsMongoid 多态关联 Rails
【发布时间】: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


    【解决方案1】:

    我已经设法根据link 中的以下答案实现了一个非优雅的工作解决方案

    【讨论】:

    • StackOverflow 是一个征求意见、获得帮助和检索反馈的社区。请分享您的部分代码,人们可能会发现它很有用。如果你只说“我得到了解决方案”,其他人无法学习,但也许他们需要一个例子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    相关资源
    最近更新 更多