我正在创建一个应用程序来轮询用户。我从本教程开始并对其进行了修改。我还在这里发布了另一个关于它的问题。每个用户都有一个投票权重。到目前为止用户可以投票并显示每个选项的投票计数(根据用户的投票权重计算)。
我现在要做的是设置一个条件,检查该民意调查的任何选项是否已达到 50%。
投票.rb
class Vote < ApplicationRecord
belongs_to :user
belongs_to :vote_option
end
投票选项.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
民意调查
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 显示
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
所以在 polls/show.html.erb 上我需要类似的东西:
<% if option.get_vote_count.any > 50 %>
do something
<% end %>
如何修复上面的代码以使其正常工作?我应该在 show action 下的 polls_controller 上添加什么?
提前致谢。
这就是解决方案。感谢@Ash 为我指明了正确的方向:
<% @poll.vote_options.each do |option| %>
<% if option.get_vote_count > 50 %>
<h4> Condition met! </h4>
<% end %>
<% end %>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句