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