检查用户是否对范围进行了投票 [英] Check if a user has voted with scope

查看:120
本文介绍了检查用户是否对范围进行了投票的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用可投票行为来实施网络民意调查.通过两种选择,可以轻松确定用户是否已投票.

I am using acts as voteable to implement a web poll. With two choices it is simple to determine whether a user has voted or not.

@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

我需要自定义多项选择,并已基于此实现了: 如何设置多个行为投票制的选项投票系统?

I need to has custom multiple choices and have implemented it based upon this: How do I setup a multi-option voting system using acts-as-votable?

以上项目指出,您可以检查用户是否已使用voted_for投票?但这确实包括范围内的项目:

The item above states you can check if a user has voted with voted_for? however this does include scoped items:

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

我的问题是确定使用范围时用户是否已投票的最佳方法是什么?我是否需要遍历并单独检查每个记录的每个范围?

My question is what is the best way to determine if a user has voted when using scopes? Do I need to loop through and check each scope individually for each record?

编辑1

当前,我具有以下轮询实例方法:

Currently I have the following Poll instance method:

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并获得已投票的列表:

It looks like you should be able to call Poll.first.votes_for and get a list of the votes that have been cast:

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相匹配:

With that list you should be able to check if any of the voter_ids matches the User you are looking for:

p.votes_for.any? { |v| v.voter_id == u.id }
=> true 

这篇关于检查用户是否对范围进行了投票的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆