简体   繁体   English

Ruby on Rails act_as_votable宝石

[英]Ruby on Rails acts_as_votable gem

I am trying to create a voting system using acts_as_votable gem in Rails 4. I have three nominees to be voted from and I want a voter to choose from any of those three and vote only one nominee.acts_as_votable gem allows voter to vote multiple nominees. 我正在尝试使用Rails 4中的acts_as_votable gem创建一个投票系统。我有三名候选人需要投票,我希望一个投票者从这三个候选人中选择一个,然后只投票给一个nominee.acts_as_votable允许投票者投票多个候选人。 How do I restrict to only one nominee? 我如何只限制一名候选人?

If you keep track of the nominees you can add a before_action in your controller that checks if the current_user has already cast his vote. 如果您跟踪被提名者,则可以在控制器中添加一个before_action,以检查current_user是否已经投票。 If so, flash an error and redirect them etc. 如果是这样,请刷新错误并重定向它们,等等。

you can write a before_action callback to check if current_user has already voted or not only before the vote action is called. 您可以编写一个before_action回调来检查current_user是否已经投票,或者仅在调用vote动作之前检查。 For example 例如

before_action: :check_if_voted, only: :vote

def check_if_voted
  if current_user.voted_for?(@nominee1) || current_user.voted_for?(@nominee2) || current_user.voted_for?(@nominee3)
    flash[:notice] = "You have cast your vote already."
  end
end

And I believe you are using radio button in you form. 而且我相信您在表单中使用了单选按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM