使用 counter_cache rails 4 以百分比计算

make count in percentage by using counter_cache rails 4

我需要votes_count百分比

我的关系是

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

就像你已经写的一样:

@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

celebrity.rb中你写方法percentage_of_votes它会returnpercentage值,从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