'commentable' 多态关联如何在 'user' 模型本身上工作?

How would a 'commentable' polymorphic association work on a 'user' model itself?

我正在学习 rails 并尝试多态关联。我在下面列出了几个简单的模型以供说明。模型关联似乎按预期工作正常。但是,如果用户(评论者)想为另一个用户发表评论怎么办?我似乎无法让它与这些配置一起工作。我该怎么做?

class User < ApplicationRecord
  #  username, email, password_digest
  has_many :comments, as: :commentable, dependent: :destroy
end

class Project < ApplicationRecord
  # title, completed, user_id
  has_many :comments, as: :commentable, dependent: :destroy
end

class Comment < ApplicationRecord
  # commenter_id, commentable_type, commentable_id, body
  belongs_to :commentable, polymorphic: true
end

在控制台中...设置

user1 = User.frist
user2 = User.last
project = Project.first

pro_comment = project.comments.new(body: 'some text')
pro_comment.commenter_id = user1.id
pro_comment.save

user_comment = user2.comments.new(body: 'some text')
user_comment.commenter_id = user1.id
user_comment.save

预期和实际结果

Comment.all => successfully lists pro_comment & user_comment

But...
Comment.find_by(commenter_id: 1) => only listed the pro_comment 
(what am I doing wrong?)

还有.. user1.comments => 返回一个空对象...需要 2 个对象, 正如您在下面看到的,它没有引用 'commenter_id' .... 结果...

comment Load (0.5ms)  SELECT  "comments".* FROM "comments" WHERE 
"comments"."commentable_id" =  AND "comments"."commentable_type" =  
LIMIT   [["commentable_id", 1], ["commentable_type", "User"], 
["LIMIT", 11]]
=> #<ActiveRecord::Associations::CollectionProxy []>

我也试过了... user1.comments.where(commenter_id: 1) >> 返回...

comment Load (0.4ms)  SELECT  "comments".* FROM "comments" WHERE
 "comments"."commentable_id" =  AND "comments"."commentable_type" =  
AND "comments"."commenter_id" =  LIMIT   [["commentable_id", 1],
["commentable_type", "User"], ["commenter_id", 1], ["LIMIT", 11]]
=> #<ActiveRecord::AssociationRelation []>

不确定我做错了什么。有人可以指出我正确的方向吗? 感谢您的宝贵时间。

find_by returns只有一条记录,请尝试Comment.where(commenter_id: 1)

因为 user1.comments 是空的,所以你在混合关系。您应该有 2 个关系:评论属于可评论对象(项目或用户),评论也属于评论者(您设置为 commenter_id 的用户)。

user1.comments 为空是有道理的,因为用户是两条评论的评论者,而不是评论者。 user2.comments 不应为空,与 project.comments

相同

尝试这样的事情:

class User < ApplicationRecord
  has_many :comments_done, class_name: 'Comment', inverse_of: :commenter
  has_many :comments, as: :commentable, dependent: :destroy
end

class Comment < ApplicationRecord
  belongs_to :commenter, class_name: 'User'
  belongs_to :commentable, polymorphic: true
end

(查看指南,我可能缺少一些配置选项 https://guides.rubyonrails.org/v5.2/association_basics.html#has-many-association-reference

现在您可以使用 user1.comments_doneuser1.comments 来表示由用户完成的评论和由用户完成的评论。