0

我有这种多态关联,其中用户可以有很多评论,学校可以有很多评论,并且评论可以有很多评论(或者在我的命名情况下回复):

class Comment < ActiveRecord::Base
  attr_accessible :content
  has_many :replies, :as => :commentable, :class_name => "Comment" # replies to comments

  belongs_to :commentable, :polymorphic => true
  belongs_to :commentor, :class_name => "User", :foreign_key => "user_id"
end

class User < ActiveRecord::Base
  has_many :comments, :as => :commentable
  has_many :commentors, # all users who commented on a user
    :through => :comments,
    :source => :commentor
end

class School < ActiveRecord::Base
  has_many :comments, :as => :commentable
  has_many :commentors, # all users who commented on a school
    :through => :comments,
    :source => :commentor
end

在用户中,我可以检索所有使用@user.commentors. 学校也是如此,即@school.commentors.

对于评论模型,我想为评论模型实现相同的目标,我可以在其中找到评论的所有评论者(或者我猜是回复者);但是,我不知道要创建什么样的关联,因为 has_many :through 关联不会像用户和学校模型那样工作。

4

1 回答 1

0

用这个:

has_many :reply_commentors, :through => :replies, :source => :commentor
于 2012-09-13T14:16:50.327 回答