一个模型中相同类型的多个多态关系 - MongoID

Multiple polymorphic relations of same type in one model - MongoID

我不知道如何正确使用标题,让我解释一下。

我有我的 class 赞:

class Like
  include Mongoid::Document
  belongs_to :likable, polymorphic: true
  belongs_to :user
end

class Submission
  include Mongoid::Document

  belongs_to :creator, class_name: 'User', inverse_of: :submissions
  has_many :likes, :as => :likable, :dependent => :destroy
end

然后是导致问题的class:

class User
  include Mongoid::Document
  has_many :submissions, :dependent => :destroy

  has_many :liked_submissions, :as => :likable, :dependent => :destroy, class_name: 'Like'
  has_many :liked_comments, :as => :likable, :dependent => :destroy, class_name: 'Like'
end

现在,问题是我不知道如何在用户 class 中正确地同时拥有 'liked_comments' 和 'liked_comments'。当我像上面那样拥有它时,出现错误:Ambiguous relations :liked_submissions, :liked_comments defined on User. 尝试为提交创建一个赞时。

我环顾四周,发现了一个Github issue,说这可能是不可能的,但我又找不到这个issue,我什至不确定它是否与这个问题。

这可能吗?如果不可能,有什么绕过它的建议吗?我也想在 BlogPost 模型中使用喜欢,但如果这不起作用,我将不得不找到另一种方法。

提前致谢。

我试过了,它可以使用 mongoid 版本 4.0.2:

class Like
  include Mongoid::Document

  belongs_to :likable, polymorphic: true
  belongs_to :user, inverse_of: :user
end

class Submission
  include Mongoid::Document

  belongs_to :creator, class_name: 'User', inverse_of: :submissions
  has_many :likes, as: :likable, dependent: :destroy
end

class User
  include Mongoid::Document

  has_many :submissions, dependent: :destroy

  has_many :likes, as: :user
  has_many :liked_submissions, as: :likable, dependent: :destroy, class_name: 'Like'
  has_many :liked_comments, as: :likable, dependent: :destroy, class_name: 'Like'
end

class BlogPost
  include Mongoid::Document

  has_many :likes, as: :likable, dependent: :destroy
end

此外 user.liked_submissionsuser.liked_comments 是相同的关系,所以它等同于声明这样的别名:

class User
  include Mongoid::Document

  has_many :submissions, dependent: :destroy

  has_many :likes, as: :user
  has_many :liked_submissions, as: :likable, dependent: :destroy, class_name: 'Like'

  alias :liked_comments :liked_submissions
end

发现这个问题后遇到了困难,但找到了很酷的解决方案

添加到您的 Gemfile

gem 'mongoid-multiple-polymorphic'

这很有魅力:

  class Resource

  has_one :icon, as: :assetable, class_name: 'Asset', dependent: :destroy, autosave: true
  has_one :preview, as: :assetable, class_name: 'Asset', dependent: :destroy, autosave: true

  end