0

I have a game, which creates logs. On display of the logs, I'd like to group them by turn to create an overall table, with a nested table for each turn within. In order to accomplish this, I am trying to group the logs by turn, so I can then iterate over them with an outer loop that runs once per turn, and an inner loop for each log item within that turn.

Right now, I have:

# logs_controller.rb
@logs = @game.logs.order("created_at ASC").group(:turn)

and in the view:

# logs/index.html.erb
<% @logs.each do |turn_logs| %> <table class="table">
    <tr>
        <td><%= turn_logs.first.turn%></td>
        <td>
            <table class="table table-striped">
                <% turn_logs.each do |log| %>
                    <tr><td><%= log.text %></td></tr>
                <% end %>
            </table>
        </td>
    </tr>
</table>

This doesn't work, since Postgres complains that:

ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  column "logs.id" must appear in the GROUP BY clause or be used in an aggregate function

I'm sure there's a simple way to do this that I'm overlooking, and I'll slap my head when it's pointed out, but right now it's eluding me.

ekad
  • 14,436
  • 26
  • 44
  • 46
Tony Zito
  • 534
  • 6
  • 11

1 Answers1

1

Okay, I've got a good solution, I think. It involves using group_by to make an array of an array of log objects, with the turn as the key:

Controller:

# logs_controller.rb
@logs_by_turn = @game.logs.order("created_at ASC").group_by {|log| log.turn}

and in the view:

# logs/index.html.erb
<table class="table">
<%  @logs_by_turn.each do |turn, turn_logs| %>  

        <tr>
            <td><%= turn_logs.first.turn %></td>
            <td>
                <table class="table table-striped">
                    <% turn_logs.each do |log| %>
                        <tr><td><%= log.text %></td></tr>
                    <% end %>
                </table>
            </td>
        </tr>
<% end %>

Tony Zito
  • 534
  • 6
  • 11