我正在使用可投票的行为来实施网络投票。有两种选择,很容易确定用户是否投票。
@user.likes @comment1
@user.up_votes @comment2
# user has not voted on @comment3
@user.voted_for? @comment1 # => true
@user.voted_for? @comment2 # => true
@user.voted_for? @comment3 # => false
@user.voted_as_when_voted_for @comment1 # => true, user liked it
@user.voted_as_when_voted_for @comment2 # => false, user didnt like it
@user.voted_as_when_voted_for @comment3 # => nil, user has yet to vote
https://github.com/ryanto/acts_as_votable
我需要自定义多项选择并基于此实现它: 如何使用acts-as-votable设置多选项投票系统?
上面的项目表明您可以检查用户是否使用 voted_for 投票?但是,这确实包括范围内的项目:
Poll.first.vote_by voter: User.first, vote_scope: 'blue'
User.first.voted_for? Poll.first #false
User.first.voted_for? Poll.first, :vote_scope => 'blue' #true
我的问题是确定用户在使用范围时是否投票的最佳方法是什么?我是否需要循环并分别检查每条记录的每个范围?
编辑 1
目前我有以下 Poll 实例方法:
def has_voted?(user)
['red', 'green', 'blue', 'white'].each do |option|
if user.voted_for? self, :vote_scope => option
return true
end
end
return false
end
Poll.first.has_voted?(User.first)