Rails: How to access two models in a single loop

200 Views Asked by At

I am using Audited gem to track the changes done on users. What I want to display exactly is the changes made which is the audits with the time they are updated at in a same row.I tried to display it this way but it makes repetitions.

<% @users.each do |user| %>
  <% user.audits.each do |audit| %>
    <% if audit.action != "create" %>
    <% user.revisions.each do |revision| %>
    <tr class="list-item">
      <td>
        <%= user.role %>
      </td>

      <td>
        <%= audit.action %>
      </td>

      <td>
        <%= audit.audited_changes %>
      </td>

      <td>
        <%= revision.created_at %>
      </td>

      <td>
        <%= revision.updated_at %>
      </td>
    </tr>
      <% end %>
    <% end %>
  <% end %>
<% end %>

What I want is to be able to display them with out displaying a single change multiple times.

I am looking for an expression like

for(i=5,j=3;j<5;i++,j++){
     ....
}

in rails, to avoid the repetition. Thank you

2

There are 2 best solutions below

0
On BEST ANSWER

I solved it this way since both audits and revision has same number of elements.I hope it helps for the others.

<% @users.each do |user| %>
      <% user.audits.each_with_index do |audit, i| %>
        <% if audit.action != "create" %>
        <% user.revisions[i] %>
        <tr class="list-item">
          <td>
            <%= user.role %>
          </td>

          <td>
            <%= audit.action %>
          </td>

          <td>
            <%= audit.audited_changes %>
          </td>

          <td>
            <%=user.revisions[i].created_at %>
          </td>

          <td>
            <%= user.revisions[i].updated_at %>
          </td>
        </tr>
        <% end %>
      <% end %>
    <% end %>
0
On

You could also try zip:

user.audits.zip(user.revisions) do |audit, revision|