如何使用作为投票的行为设置多选项投票系统? [英] How do I setup a multi-option voting system using acts-as-votable?
问题描述
我想使用 acts-as-votable 来实现一个投票系统,我可以在其中提供多个自定义选项 - 例如5 个按钮(蓝色"、红色"、绿色"、灰色"、白色").
I want to use acts-as-votable to implement a voting system where I can supply multiple custom options - e.g. 5 buttons ('blue', 'red', 'green', 'grey', 'white').
我希望我的用户只能选择其中一种颜色,但我希望能够统计每个项目的所有投票(10 - 蓝色,4 - 红色等).
I want my users to be able to choose only 1 of those colors, but I would like to be able to tally up all the votes (10 - blue, 4 - red, etc.) per item.
我觉得我会使用投票范围,但我不太确定如何使用.
I feel like I would use vote-scopes, but I am not quite sure how.
我如何通过行为投票来做到这一点?
How do I do this with acts-as-votable?
推荐答案
看起来很简单:
https://github.com/ryanto/acts_as_votable#examples-with-scopes
@item.vote_by voter: @user1, vote_scope: 'blue'
@item.vote_by voter: @user2, vote_scope: 'red'
@item.votes_for.size # => 2
@item.find_votes_for(vote_scope: 'blue').size # => 1
@item.find_votes_for(vote_scope: 'red').size # => 1
因此,您的页面上需要一组 5 个单选按钮(5 种颜色)供用户选择,并将选定的参数发送到控制器,您将在那里使用选定的颜色创建投票.
So you'll need a set of 5 radio buttons (for 5 colors) on your page for the user to select from, and send the selected params to controller where you'll create the vote with selected color.
然后您可以检查用户是否为此项目投票并禁用未来的投票:
Then you can check if user voted for this item and disable the future voting for it:
@user.voted_for? @item # => true
<小时>
根据评论更新
params: {id: 1, scope: 'green'}
@item = Item.find(params[:id])
scope = params[:scope]
if ['red', 'blue', 'green'].include? scope
@item.vote_by voter: current_user, vote_scope: scope
else
# show error message
end
这篇关于如何使用作为投票的行为设置多选项投票系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!