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?
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?
Edit 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)
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">]>
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