Stéphane V
Stéphane V

Reputation: 1094

acts-as-votable : Get an array of voters with names and date of voting

How to get the list of user names that voted for a post, including their id and date of vote ?

Here is my (working) solution....

voters = []
item.votes_for.each do |vote|
    voters << { updated_at: vote.updated_at, voter_id: vote.voter_id, voter_name: User.find(vote.voter_id).name }
end
json.voters voters
json.up_votes voters.count

I found that far from optimal... Especially because of the addtional query to User.find(...) which can lead to multiple queries when there is a lot of votes.

Is there a more "railsy" way to implement that ?

item.votes_for.voters provides a link to the user Model, but there is no acces to the date of vote if I do that....

Thank you.

Upvotes: 0

Views: 249

Answers (1)

Xavier Delamotte
Xavier Delamotte

Reputation: 3599

I would suggest to use includes to include the voters in your votes when you request them.

voters = item.votes_for.includes(:voter).map do |vote|
     { updated_at: vote.updated_at, voter_id: vote.voter_id, voter_name: vote.voter.name }
end

Upvotes: 4

Related Questions