forked from pilotcreative/vote_fu
-
Notifications
You must be signed in to change notification settings - Fork 75
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Calculating total karma for a user #110
Comments
To sum all votes for posts for a particular user:
`User.find(...).posts.map(&:votes_for).sum`
To sum all votes for subtracted from votes against for a particular user,
who created posts: `User.find(...).posts.map(&:plusminus).sum`
If you're doing this often, it would be worthwhile to denormalize this to
the User model.
|
Thanks, that was exactly what I was looking for. I tried to search online for what you mean by denormalize this to the User model. Would you mind explaining or adding an example? Do you mean create a method in the model like:
|
By denormalize, I mean you can store the computed value on the User model
(if you have lots of posts, would be useful, but not necessary - just for
performance reasons).
By the way, you should generally name your methods with adjectives/nouns,
not verbs/adverbs, in Ruby convention. A.k.a., not `get_karma`, but `karma`.
Something like:
```ruby
class User
def votes_for_all_posts
# Create an integer field `votes_for_all_posts` on User, and make sure
Post has an index on `created_at`.
if posts.order('created_at ASC').first.created_at > created_at
v = posts.map(&:votes_for).sum
write_attribute(:votes_for_all_posts, v)
v
else
read_attribute(:votes_for_all_posts)
end
end
end
```
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What would be the best way to calculate the total number of votes a user has received? (ie: tally all votes from posts a user created).
Would the best approach be to create a counter that increments everytime a vote is cast? Or is there a built in method that can tally the total?
The text was updated successfully, but these errors were encountered: