creativetim creativetim - 4 months ago 22
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.

poll.rb

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)
end

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

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

def score
self.reputation_for(:score).to_i
end
end


voter.rb

class Voter < ActiveRecord::Base
has_many :polls

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

def powervotes
self.reputation_for(:powervotes).to_i
end
end


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

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!

voter.rb

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

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