我使用行为投票来实施网络投票。通过两种选择,可以很容易地确定用户是否已投票。
@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
我需要自定义多个选项并基于此实现它: How do I setup a multi-option voting system using 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)
答案 0 :(得分:1)
看起来您应该可以致电Poll.first.votes_for
并获取已投票的投票列表:
p.votes_for
=> #<ActiveRecord::Associations::CollectionProxy [#<ActsAsVotable::Vote id: 1,
votable_type: "Poll", votable_id: 1, voter_type: "User", voter_id: 1, vote_flag: true,
vote_scope: "blue", vote_weight: 1,
created_at: "2017-11-05 22:12:52", updated_at: "2017-11-05 22:12:52">]>
使用该列表,您应该可以检查voter_ids
是否与您要查找的User
匹配:
p.votes_for.any? { |v| v.voter_id == u.id }
=> true