creativetim creativetim - 1 year ago 82
Ruby Question

Twitter ActiveRecord Reputation: Counting primary reputations as non-primary reputations

I have two models: Voters and Polls.

A Voter can vote on a Poll in two ways: 1) up/down vote 2) power vote

I have up/down voting working, but I want to be able to know how many power votes a user has accumulated in aggregate as they can only have a certain amount.


class Poll < ActiveRecord::Base
belongs_to :voter

has_reputation :votes,
source: :voter

has_reputation :powervotes,
source: :voter,
source_of: [{reputation: :voter_powervotes, of: :voter}]

has_reputation :score,
source: [
{ reputation: :votes },
{ reputation: :powervotes, weight: 2 }]

def upvote(voter)
self.add_or_update_evaluation(:votes, 1, voter)

def downvote(voter)
self.add_or_update_evaluation(:votes, -1, voter)

def powervote(voter)
self.add_or_update_evaluation(:powervotes, 1, voter)

def score


class Voter < ActiveRecord::Base
has_many :polls

has_reputation :voter_powervotes,
source: [reputation: :powervotes, of: :polls]

def powervotes

When I powervote() on a poll as a user and then call Voter.powervotes it returns 0. What gives? I feel like it was a miracle that I got this far on my own, but now I'm just lost. Maybe this isn't possible and I just need to manually query the database?

Answer Source

Here's a simple solution that was found with the help of the gem's creator Katsuya Noguchi. There's no need to create a :voter_powervotes reputation inside of the voter model when you can just count by whom the power_votes were evaluated by. I def felt like a dolt after seeing how simple it was. Hopefully this helps someone else!


def powervotes
  Poll.evaluated_by(:power_votes, self).count.to_i

GitHub issue reference: #63 STI pulls wrong target_id for non-primary reputation

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