检查用户是否已对范围进行投票

Check if a user has voted with scope

我正在使用 acts as voteable 来实施网络投票。有两个选择,很容易确定用户是否已投票。

@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

我需要自定义多项选择并基于此实现了它:

上面的项目说明您可以检查用户是否已投票 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)

看来您应该可以调用 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