0

i want to achieve a nested loop without duplicates in a have and belongs to many relationship

i have a model 'campaign' and for each campaign i also have campaign data.

i want to display each campaign with its campaign data in a table. (nested)

@campaigns = current_user.campaigns
 <% @campaigns.each do |item| %>
          <% i = item.campaign_data %>
            <% i.each do |cdata| %>
            <%= cdata.date %>
            <tr>
              <td>
              <%= item.name %>
              </td>
              <td>
              <%= cdata.date %>
              </td>
              <td>
              </td>
            </tr>
          <% end %>
          <% end %>

my problem is that my campaigns get duplicated.

I want to achieve something like this:

Each campaign is listed in the table with its corresponding campaign_data directly below it, and if no campaign_data is left the next loop begins with the next campaign - is this possible?

best regard

1 Answers1

0

You might be getting duplicated campaigns as you are using <%= item.name %> inside the <% i.each do |cdata| %> loop. So, if one campaign has 4 campaign_datas you will see the campaign name 4 times.

You should use naming conventions properly, if the campaign has many data campaign_data then you should specify so in association i.e. has_many :campaign_datas

Also, the Following code should be in the controller

@campaigns = current_user.campaigns.include(:campaign_datas)

Note:- I used include to avoid n + 1, please read here.

In view

<% for campaign in @campaigns %>
  <% next if @campaigns.campaign_datas.blank? %>
  <tr>
    <td><%= item.name %></td>
  </tr>
  <% for campaign_data in @campaigns.campaign_datas %>
    <tr>
      <td><%= campaign_data.date %></td>
    </tr>
  <% end %>
<% end %>

Note:- <% next if @campaigns.campaign_datas.blank? %> line is used to skip the campaign if it has no campaign data.

Salil
  • 46,566
  • 21
  • 122
  • 156