“可评论的”多态关联如何在'用户'模型本身上起作用?

问题描述 投票:0回答:1

我正在学习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 []>

不知道我做错了什么。有人可以指出我正确的方向。我感谢你的时间。

ruby-on-rails polymorphic-associations
1个回答
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进行用户完成的评论并在用户处完成。

© www.soinside.com 2019 - 2024. All rights reserved.