Dingo Dingo - 1 year ago 83
Ruby Question

Get value of votes from users posts

I have a model

in which a user can post a snippet. The snippet that they post can be voted on using the
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?

Answer Source

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 }




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download