我正在创建一个用于轮询用户的应用。我从this tutorial开始修改它。我还发布了另一个有关它的问题here。 每个用户都有投票权重。到目前为止,用户可以显示每个选项的投票和投票计数(根据用户的投票权重计算)。
我现在要做的是设置一个条件,检查该民意调查的任何选项是否已达到50%。
vote.rb
class Vote < ApplicationRecord
belongs_to :user
belongs_to :vote_option
end
vote_option.rb
class VoteOption < ApplicationRecord
belongs_to :poll
validates :title, presence: true
has_many :users, through: :votes
has_many :votes, dependent: :destroy
def get_vote_count
Vote.joins(:vote_option).joins(:user).where("vote_options.id = #{self.id}").sum(:vote_weight)
end
end
poll.rb
class Poll < ApplicationRecord
validates :question, presence: true
validates :division, presence: true
validates :open_date, presence: true
validates :close_date, presence: true
before_save :set_position
set_sortable :sort, without_updating_timestamps: true
has_many :comments, as: :commentable
has_many :votes, :through => :vote_options
has_many :vote_options, dependent: :destroy
belongs_to :division
belongs_to :user
has_and_belongs_to_many :users
accepts_nested_attributes_for :vote_options, :reject_if => :all_blank, :allow_destroy => true
accepts_nested_attributes_for :users
def normalized_votes_for(option)
votes_summary == 0 ? 0 : (option.get_vote_count.to_f / votes_summary) * 100
end
def votes_summary
vote_options.inject(0) {|summary, option| summary + option.get_vote_count}
end
end
polls_helper.rb
module PollsHelper
def visualize_votes_for(option)
content_tag :div, class: 'progress' do
content_tag :div, class: 'progress-bar',
style: "width: #{option.poll.normalized_votes_for(option)}%" do
"#{option.get_vote_count}"
end
end
end
end
polls_controller show
def show
@poll = Poll.includes(:vote_options).find_by_id(params[:id])
@vote = Vote.find_by_id(params[:id])
@users = @poll.users
@comments = Comment.with_details.all
end
所以在民意调查/ show.html.erb上我需要类似的东西:
<% if option.get_vote_count.any > 50 %>
do something
<% end %>
如何修复上面的代码才能使其正常工作?我应该在show action下的polls_controller上添加什么?
提前致谢。
答案 0 :(得分:0)
这是解决方案。感谢@Ash指出了正确的方向:
<% @poll.vote_options.each do |option| %>
<% if option.get_vote_count > 50 %>
<h4> Condition met! </h4>
<% end %>
<% end %>