2

Here's what I am trying to achieve:

Group_x.name

member1.name -- member1.join_date -- etc
member2.name -- member2.join_date -- etc ...

Group_y.name

member1.name -- member1.join_date -- etc
member2.name -- member2.join_date -- etc ...

What I'm going for is really very similar to this although the implementation there doesn't work for me.

I've gotten this far in my controller:

def index
  # https://stackoverflow.com/a/17835000/2128691
  @user_group_ids = current_user.student_groups.map(&:id)
  @students = Student.where('student_group_id IN (?)', @user_group_ids)
  # https://stackoverflow.com/a/10083791/2128691
  @students_by_group = @students.uniq {|s| s.student_group_id}
  @title = "All students"
end  

and calling the following in my view -

<% @students_by_group.all.each do |x| %>
  <p>
    <%= "#{x}" %>
  </p>
<% end %>   

gives me a list of all student objects. if i call <%= "#{x.name}" %> or <%= "#{x.created_at}" %>, etc, I get the correct information, and everything is great.

But now that I have all this information, how can I put the group.name (in my code it would be x.student_group.name) as a header for all of the students for which that group_name is true?

Community
  • 1
  • 1
dax
  • 10,779
  • 8
  • 51
  • 86

1 Answers1

3

I think you need to use group_by on @students_by_group like this:

@students_by_group = @students_by_group.group_by { |s| s.student_group }

This would return a hash with the keys being the student group objects and the values being the students that belongs to this group, then you can do this in your view:

<% @students_by_group.each do |group, students| %>
  <h3><%= group.name %></h3>
  <% students.each do |x| %>
    <p>
      <%= "#{x}" %>
    </p>
  <% end %>
<% end %>

As an additional note, the group_by would fire a query for each student, so you may want to eagerly load the student group for each student like this for some performance gain:

@students = Student.where('student_group_id IN (?)', @user_group_ids).includes(:student_group)
Ahmad Sherif
  • 5,923
  • 3
  • 21
  • 27