2017-11-05 3 views
0

私は、投票をWeb投票を実装するために使用しています。 2つの選択肢から、ユーザーが投票したかどうかを簡単に判断できます。ユーザーがスコープで投票したかどうかを確認します。

@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

現在、私は、次のポーリングインスタンスメソッドを持っています。

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

Userあなたが探しているatches 'Poll.first.find_votes_for(vote_scope: '青')。voters'? – mindlis

+0

はい、私は10のオプション、赤、青、緑の投票がある場合...ユーザーが投票に投票したかどうかを判断するために、各投票に10をすべてチェックする必要があります。私が1000の投票を持っていて、ユーザーが投票したものがどれが遅いか知りたいのですが。 – Dercni

+0

あなたが聞いていることを誤解している可能性があります – mindlis

答えて

1

あなたがPoll.first.votes_forを呼び出し、キャストされている投票のリストを取得することができるはずのように見えます:あなたがvoter_idsメートルのいずれかどうかを確認することができるはず、そのリストで

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">]> 

何をしようとした場合、リンクされた答えから

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

優れています。あなたのコードとの違いを説明できますか? p.votes_for.where(voter_id:u.id).any? – Dercni

+0

Mineはクエリの結果を繰り返し処理し、結果があるかどうかを確認します。実際には、クエリの結果を確認するだけで効率的ですので、私はあなたの行を使用します。 – mindlis

関連する問題