使用counter_cache rails 4进行百分比计数

时间:2015-09-04 04:27:48

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

我需要以百分比进行投票_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

如何以千分比形式投票_count?投票/总票数投票* 100

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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