【发布时间】:2012-09-05 03:16:09
【问题描述】:
我有这种多态关联,其中一个用户可以有很多 cmets,一个学校可以有很多 cmets,一条评论可以有很多 cmets(或者在我的命名情况下回复):
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。
对于 cmets 模型,我希望为 Comments 模型实现相同的目标,在该模型中我可以找到评论的所有评论者(或者我猜是回复者);但是,我不知道要创建什么样的关联,因为 has_many :through 关联不会像在 User 和 School 模型中那样工作。
【问题讨论】:
-
这行得通吗? has_many :reply_commentors, :through => :replies, :source => :commentor
-
哦,是的,这行得通。哇,我当时太傻了。谢谢。
-
如果您想接受,我将我的评论添加为答案。
标签: ruby-on-rails polymorphic-associations