我无法弄清楚如何正确使用标题,所以让我解释一下。
我的班级喜欢:
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 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
现在,问题在于我无法弄清楚如何正确地同时拥有“喜欢的评论”。和' likes_comments'在用户类中。如上所述,当我尝试为提交创建类似内容时,我会收到错误:Ambiguous relations :liked_submissions, :liked_comments defined on User.
。
我环顾四周,发现一个Github问题说这可能是不可能的,但我再也找不到这个问题了,我甚至不确定它是否与这个问题有关
这是否可行,如果没有,是否有任何建议可以绕过它?我也希望在BlogPost模型中使用喜欢,但如果这不起作用,我将不得不寻找另一种方式。
提前致谢。
答案 0 :(得分:2)
我试过这个并使用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_submissions
和user.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
答案 1 :(得分:1)
在发现这个问题之后遇到了困难时期但是得到了很酷的解决方案
添加到您的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