mercredi 9 septembre 2015

Counter cache in rails 4

I am using counter_cache for counting the votes. A user can able to do one upvote and downvote.

My model

vote.rb

attr_accessible :celebrity_id, :user_id, :vote_dvote
belongs_to :user
belongs_to :celebrity, counter_cache: true

celebrity.rb

attr_accessible :name, :gender, :category_id, :votes_count  
belongs_to :user
belongs_to :category
has_many :votes

def total_upvotes
    Vote.where('vote_dvote = ?', true).count
end

def percentage_of_votes
    (self.votes_count.to_f / self.total_upvotes.to_f * 100.0).round(2)
end     

Controller

def show_ranking              
  @celebrities = Celebrity.includes(:category).order(votes_count: :desc)      
  @celebrities.each do |celeb|
    celeb["votes_count"] = celeb.percentage_of_votes                
  end
end

both upvote and downvote saved in votes table, for upvote 'vote_dvote=1'and for downvote 'vote_dvote=0', votes_count for each celebrity is saved in celebrities table. what happening in my case is votes count is more than the total upvote count. So I can't able to get the exact percentage.

But I need only upvote count. Can anyone please help me out here

Aucun commentaire:

Enregistrer un commentaire