Search code examples
ruby-on-railsrubyacts-as-votable

Get value of votes from users posts


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?


Solution

  • 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