0

我正在使用可投票的行为来实施网络投票。有两种选择,很容易确定用户是否投票。

@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)
4

1 回答 1

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 
于 2017-11-05T22:21:48.823 回答