Nick Vanderbilt
Nick Vanderbilt

Reputation: 2535

How do I get commenters for a blog

I am using Rails 3.2.

I have following models:

Blog
Comment
User

class Blog < ActiveRecord::Base
  has_many :comments
end

I want a list of commenters for a given blog.

I want something like

   class Blog < ActiveRecord::Base
      has_many :comments
      has_many :commenters, ...fill in the blank...
    end

@blog.commenters should return an array of User instances.

What should I fill the blanks with above.

Upvotes: 0

Views: 66

Answers (1)

Matthew Rudy
Matthew Rudy

Reputation: 16844

I guess you have the following

class User
  has_many :comments
end

class Comment
  belongs_to :blog
  belongs_to :user
end

class Blog
  has_many :comments
end

All you need to add is

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

Note: the :source is needed because the relation on comments is not called commenters

Upvotes: 1

Related Questions