rubyist
rubyist

Reputation: 11

Counting voted comments

i have 3 models

user

has_many :comments
has_many :votes

comment

belongs_to :user
has_many :votes

vote

belongs_to :user
belongs_to :comment

I want to find if user has any voted comments. Any help will be appreciated.

Upvotes: 1

Views: 85

Answers (2)

Aaric Pittman
Aaric Pittman

Reputation: 558

You could also add a counter cache to your Comment model for the number of votes it has. Then you could do:

user.comments.where("vote_count > 0")

Or better yet you could then define a method on the Comment model:

def with_votes  
  where("vote_count > 0")  
end

And then you could call:

user.comments.with_votes

Upvotes: 1

fl00r
fl00r

Reputation: 83680

user.comments.joins(:votes).select("distinct comments.id, comments.*")

or you can use scope

class Comment < ActiveRecord::Base
  belongs_to :user
  has_many :votes
  scope :with_votes, joins(:votes).select("distinct comments.id, comments.*")
end

#=> user.comments.with_votes

Upvotes: 1

Related Questions