-1

I have a model snippets in which a user can post a snippet. The snippet that they post can be voted on using the acts_as_votable gem. This is working perfectly, and when a user votes, the vote count of the snippet increases by one.

Although, I am wondering is there a way to get the total value of votes for one user's snippets they have posted?

So if a user posted 4 snippets, each with a value of 2 votes, then I am trying to get the total value of only their snippets - which is 8.

This code is used to get the votes of one individual snippet:

<%= @snippet.weighted_score %>

Although how am I able to get the total value of one users posted snippets?

2 Answers2

0

you can always see all the votes of a user by doing @user.votes

check out acts_as_voter the the documentation here, it already does whatever you want.

fenec
  • 5,637
  • 10
  • 56
  • 82
0

I'm assuming you have the relationship user has_many snippets set up? If thats the case you should be able to get all the snippets associated with the user and sum up the votes_for.

user.snippets.sum { |s| s.votes_for.size }

Edit: or in your case:

user.snippets.sum { |s| s.weighted_score }

References:

http://apidock.com/rails/Enumerable/sum

https://github.com/ryanto/acts_as_votable

hajpoj
  • 13,299
  • 2
  • 46
  • 63
  • thats up to you. you could make a method in the `User` model like `def score; snippets.sum { |s| s.weighted_score }; end` and then from your view call `<%= @user.score %>` or you could directly call `<%= @user.snippets.sum { |s| s.weighted_score } %>` in the view though this isn't as clean. – hajpoj Nov 23 '16 at 00:21