2015-09-04 91 views
0

我需要使用百分比的votes_count。通过使用counter_cache轨道进行百分比计数4

我的关系是

celebrity.rb

has_many :votes 

vote.rb

belongs_to :celebrity, counter_cache: true 

我控制器

def show_celebrity 
    @celebrity = Celebrity.includes(:category).where('category_id = ?', params[:id]) 
    @celebrity.each do |celeb| 
    celeb["votes_count"] = celeb.votes.count 
    end 
    respond_to do |format| 
    format.json { render json: @celebrity } 
    end 
end 

我怎样才能使百分比的votes_count?票数/总数票* 100

回答

1

就像你已经写:

@celebrity = Celebrity.includes(:category).where('category_id = ?', params[:id]) 
total_votes = Vote.count.to_f 

@celebrity.each do |celeb| 
    celeb["votes_count"] = (celeb.votes_count/total_votes * 100).round(2) 
end 
0

celebrity.rb你写的方法percentage_of_votes它将返回percentage值,从controller

class Celebrity < ActiveRecord::Base 
    # your code goes here.... 
    def total_votes 
    Vote.count 
    end 

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

调用controller调用方法percentage_of_votes

def show_celebrity 
     @celebrity = Celebrity.includes(:category).where('category_id = ?', params[:id]) 
     @celebrity.each do |celeb| 
     celeb["votes_count"] = celeb.percentage_of_votes 
     end 
     respond_to do |format| 
     format.json { render json: @celebrity } 
     end 
    end