From many to many

User.rb
has_many :votes
has_many :photos


Photo.rb
has_many :votes
belongs_to :user

Vote.rb
belongs_to :user
belongs_to :photo

I want to list the users who voted for the photo. But this list should contain information about how many times the user voted for the photo. For example, when I go to url photos / 5 / statistics There should be a list, as shown below:

1) User1   voted 30 times
2) User432 voted 15 times
3) User43  voted 12 times

Any help would be appreciated.

+3
source share
3 answers

Using group_by would be one way to do this.

For instance:

Photo.first.votes.group_by(&:user).each do |user, votes| 
  puts "User #{user.id} voted #{votes.count} times"
end
+5
source

So, basically you work within the framework of the Photo model:

class Photo < ActiveRecord::Base
  ...
  def voting_list
    votes.joins(:user).group(:user).count
  end
  ...

This will give you an OrderedHash, as shown below:

{<user_object_1> => 14, <user_object_2> => 33, ...}
+1
source

, , - :

user = User.find_by_some_option
photo = user.photos.first
photo.votes.find{|vote| vote.user == user}.count
0
source

All Articles