0

假设我有一个UserPost一个Comment模型,它允许用户对帖子发表评论。我已经建立了一个多态关系,如下所示:

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但这不起作用。

有什么建议吗?

4

1 回答 1

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
于 2013-02-19T14:42:14.043 回答