I have a User model with attributes department and points. I have grouped the users by department and sorted each department by the number of points they contain, as shown below in my home/index view:
Accounting 158
Animal Science 98
Kinesiology 58
I simply want to get the index of each hash element in the array so I can do something like this:
1. Accounting 158
2. Animal Science 98
3. Kinesiology 58
This is the code in my home_controller:
class HomeController < ApplicationController
def index
@users = User.find(:all)
@dep_users = @users.group_by { |u| u.department}
end
And in my home/index view I have this code:
<% @dep_users.sort.each do |department, users| %>
<% @p = Array.new() %>
<%= department %>
<% for user in users %>
<% @p << user.points %>
<% end %>
<%= @p.inject(:+) %>
<% end %>
<% end %>
I have tried using each_with_index on @dep_users as such:
@dep_users.sort.each_with_index do |department, users, index|
but I keep getting this error:
undefined method 'each' for 0:FixNum when I do that
How could I get the index for each hash element in the array?
I think, it’s a bad idea to move so much logic in your views. Better way is to define new method which will return sorted array
[[department1, points1], [department2, points2]]in your model. Then call it from your controller to create an instance variable. And this variable in your view with code like thisLet html puts numbers before each item of your list.