“可注释”多态关联如何在“用户”模型本身上工作?

时间:2019-04-21 16:07:07

标签: ruby-on-rails polymorphic-associations

我正在学习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" = $1 AND "comments"."commentable_type" = $2 
LIMIT $3  [["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" = $1 AND "comments"."commentable_type" = $2 
AND "comments"."commenter_id" = $3 LIMIT $4  [["commentable_id", 1],
["commentable_type", "User"], ["commenter_id", 1], ["LIMIT", 11]]
=> #<ActiveRecord::AssociationRelation []>

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

1 个答案:

答案 0 :(得分:2)

find_by仅返回一条记录,请尝试Comment.where(commenter_id: 1)

对于user1.comments为空,您正在混合关系。您应该具有2种关系:comment属于可注释对象(项目或用户),并且注释也属于注释者(您设置为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来评论用户所做的以及在用户处所做的评论。