问题
I'm using this gem for comments: https://github.com/lml/commontator
Which is setup to easily plug into this gem to vote on the comments: https://github.com/ryanto/acts_as_votable
I'm using rails 4 btw, which is compatible with both gems.
In my User model:
class User < ActiveRecord::Base
acts_as_voter
acts_as_commentator
has_many :comments
end
In my Comment model:
class Comment < ActiveRecord::Base
acts_as_votable
belongs_to :user
end
Everything seems to be working fine. But when trying to calculate a users total votes (the total votes received on all comments by the user) (karma)
<%= @user.votes.count %>
I get this error
undefined method `votes' for #<User:0x0000010dbf23a0>
So I tried this:
<%= @user.comments.map{|c| c.votes.count}.inject(:+) %>
Which resulted in another error:
SQLite3::SQLException: no such column: commontator_comments.commontator_id: SELECT "commontator_comments".* FROM "commontator_comments" WHERE "commontator_comments"."commontator_id" = ? AND "commontator_comments"."commontator_type" = ?
I've tried:
@user.find_voted_items.count
and
@user.get_voted(Comment).count ?
and
@user.comments.collect{|c| c.votes.size}.inject(:+)
Nothing seems to work. I'm guessing it has to do with the way the commontator gem is handling the proxy associations relationship. How do I render the total number of votes received on all comments by a particular user? Any help is very much appreciated!
Edit: I did run all the migrations.
回答1:
Shouldn't you be counting votes on the comments? The User model acts_as_voter
so, according to the docs on the gem, you can retrieve a list of the items a user has voted on with find_voted_items
, but the Comment model is the one where you can count votes
since that's what the user is voting on.
Edit, given the comments. At it's simplest, you probably need something similar to this:
sum = 0
@user.comments.each do |comment|
sum += comment.votes.count
end
though you can probably make that a bit more eloquent with inject
or even with Activerecord#sum on the votes field with a carefully constructed "where clause".
来源:https://stackoverflow.com/questions/21781269/finding-user-total-votes-recieved-on-posts-by-other-users