'Rails: Inspect an array in template engine

I am maintaining a 5.2 rails app and I came across the two lines below in the template:

<%
clazzes = Clazz.joins(:staffs).includes(clazz_students: :student).where(staffs: { id: @staff.id })  
all_students = clazzes.flat_map { |clazz| clazz.clazz_students.map(&:student) }
%>

I have like to somehow inspect all_students to see what is in the array. Something like console log. Any suggestions on how I can do that?



Solution 1:[1]

You could use the debug view helper. Note that you have to change to output mode by changing <% to <%=.

<%=
clazzes = Clazz.joins(:staffs).includes(clazz_students: :student).where(staffs: { id: @staff.id })  
all_students = clazzes.flat_map { |clazz| clazz.clazz_students.map(&:student) }
debug(all_students)
%>

Sidenote: Loading and transforming data is usually done in the controller or even in the model when possible. And I would argue that those lines in a view are a code smell and make the view much harder to maintain and potentially to reuse. I suggest moving those lines into the controller method and just calling the instance variables in the view like this:

# in the controller method:
@clazzes = Clazz.joins(:staffs).includes(clazz_students: :student).where(staffs: { id: @staff.id })  
@all_students = clazzes.flat_map { |clazz| clazz.clazz_students.map(&:student) }

# in the view
<%= debug(@all_students) %>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 spickermann