用户如何评论其他用户?自我指涉?

时间:2013-02-19 14:32:14

标签: ruby-on-rails

假设我有UserPostComment模型,允许用户对帖子发表评论。我建立了如下的多态关系:

class User < ActiveRecord::Base
  has_many :comments
end

class GroupRun < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
  belongs_to :user
end

我现在想让用户对其他用户发表评论,但遇到了困难。我以为我可以按照has_many :notes, :as_commentable的方式做一些事情,但这不起作用。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您必须将此添加到您的用户模型:

class User < ActiveRecord::Base
  has_many :comments
  has_many :comments_from_other_users, :as => :commentable, :class_name => 'Comment'
end

我知道关系的名称很糟糕,但很容易理解,你可以随意改变它。

所以你应该在这之后:

current_user.comments.each do |comment|
  comment.user # author of the comment
  comment.commentable # object that you posted the comment on (GroupRun for instance)
end
current_user.comments_from_other_users.each do |comment|
  comment.user # author of the comment
  comment.commentable # user on which the comment is posted (should be equal here to current_user)
end