rai*_*101 3 activerecord ruby-on-rails ruby-on-rails-3
User.rb
has_many :votes
has_many :photos
Photo.rb
has_many :votes
belongs_to :user
Vote.rb
belongs_to :user
belongs_to :photo
Run Code Online (Sandbox Code Playgroud)
我想列出投票的用户.但是此列表必须包含有关用户投票的次数的信息.例如,当我去url photos/5/statistics必须有如下列表:
1) User1 voted 30 times
2) User432 voted 15 times
3) User43 voted 12 times
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.
使用group_by是一种方法
例如:
Photo.first.votes.group_by(&:user).each do |user, votes|
puts "User #{user.id} voted #{votes.count} times"
end
Run Code Online (Sandbox Code Playgroud)