在 Rails erb 中通过 JSONB 数组呈现each_with_index循环会导致重复



我正在尝试在视图中呈现以下内容,但结果(day和数组(是重复的。 这似乎在控制台中有效,删除时间助手无济于事。 我怀疑是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>

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

在第二次运行中,当time_typecloses_at时,您将使用to_return的内容设置@hours,这将是第一个循环的营业时间加上第二个循环的营业时间(由于<<(。这可能会导致重复。

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

相关内容

最新更新