arrays - 通过 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>
解决方案
循环上的to_return
参数是累积的。each_with_object
当 time_type 为 时opens_at
,您将营业时间归因于to_return
with <<
,然后将 @hours 设置为 的内容to_return
。
在第二次运行时time_type
,closes_at
您将设置 @hours 的内容to_return
,这将是第一个循环的营业时间加上第二个循环的营业时间(因为 <<)。这可能导致重复。
另外,我们应该调查一下tap
,它应该在那里使用一个简单each
的。
推荐阅读
- h2o - 如何在 spark 环境中使 H2OGradientBoostingEstimator 的 H2OGridSearch 可重复(再现性)?
- qt - 如何在 QMediaPlayer 中获取媒体类型(视频或音频)?
- elixir - 如何将 GraphQL Schema Stitching 与 Elixir Absinthe 一起使用?
- android - RxJava:当错误被吞下时,上游永远不会完成
- apache-kafka - Kafka KTable 将一个值附加到内存存储中
- mxnet - 如何理解 SageMaker 图像分类示例日志中的速度数字
- performance - Kubernetes NFS 挂载选项
- ios - 为什么我使用 AFNetworking 获得“内容长度”,而使用 Alamofire 却没有?
- javascript - 在javascript中循环动态对象
- wordpress - 即使没有服务器问题,Google 也不会将我的网站 b/c 索引为 500 错误