我如何获得博客的评论者

时间:2012-03-22 18:32:34

标签: ruby-on-rails-3

我正在使用Rails 3.2。

我有以下模特:

Blog
Comment
User

class Blog < ActiveRecord::Base
  has_many :comments
end

我想要一个给定博客的评论者列表。

我想要像

这样的东西
   class Blog < ActiveRecord::Base
      has_many :comments
      has_many :commenters, ...fill in the blank...
    end

@blog.commenters应该返回一个User实例数组。

我应该用上面的空白填充什么。

1 个答案:

答案 0 :(得分:1)

我猜你有以下

class User
  has_many :comments
end

class Comment
  belongs_to :blog
  belongs_to :user
end

class Blog
  has_many :comments
end

您需要添加的是

class Blog
  has_many :commenters, :through => :comments, :source => :user
end

注意:需要:source,因为comments上的关系未被称为commenters