Counting voted comments
i have 3 models
user
has_many :comments
has_many :votes
comment开发者_如何学C
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.
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
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
精彩评论