首页 > 解决方案 > 通过 JSONB 数组在 Rails erb 中渲染 each_with_index 循环会导致重复

问题描述

我正在尝试在视图中呈现以下内容,但结果(日期和数组)是重复的。这似乎在控制台中工作并且删除时间助手无济于事。我怀疑是ERB的事情。

business_hours 存储为 JSONB。

对我错过的任何提示表示赞赏。

company.schedules.last.business_hours returns

=> {"monday_opens_at"=>"08:00:00", "sunday_opens_at"=>"09:00:00", "monday_closes_at"=>"20:00:00", "sunday_closes_at"=>"18:00:00"}


<table class="table table-sm table-borderless text-sm mb-0">
        <% if company.schedules.last.business_hours? %>
          <% I18n.t('date.day_names').each do |day| %>
            <% %w[opens_at closes_at].each_with_object([]) do |time_type, to_return| %>
              <% @hours = to_return << company.schedules.last.business_hours["#{day.downcase}_#{time_type}"]
                  @hours.compact.tap do |hours| %>
                    <tr>
                      <th class="pl-0"><%= "#{day}" %></th>
                      <td class="pl-0 pr-0 text-right"><%= "#{time_helper(hours)}" %></td>
                    </tr>
                <% end %>
              <% end %>
            <% end %>
            <% else %>
            <p> no data available</p>
        <% end %>
      </table>

标签: arraysruby-on-railsjsonb

解决方案


循环上的to_return参数是累积的。each_with_object当 time_type 为 时opens_at,您将营业时间归因于to_returnwith <<,然后将 @hours 设置为 的内容to_return

在第二次运行时time_typecloses_at您将设置 @hours 的内容to_return,这将是第一个循环的营业时间加上第二个循环的营业时间(因为 <<)。这可能导致重复。

另外,我们应该调查一下tap,它应该在那里使用一个简单each的。


推荐阅读