在我的ruby on rails应用程序中,我目前正在显示每部电影的显示日期和时间:
<% if not @film.showings.blank? %>
To book click on a time below:</br>
<% @film.showings.each do |showing| %>
<%= showing.show_date.strftime("%A %e %B %Y") %>@ <%= showing.show_time.strftime("%H:%M") %><br>
<% end %>
<% else %>
<p>There are currently no showings for this film.</p>
<% end %>
这会显示如下数据:
Sunday 25 January 2015 @ 12:00
Sunday 25 January 2015 @ 16:00
Monday 26 January 2015 @ 11:00
Monday 26 January 2015 @ 22:00
Tuesday 27 January 2015 @ 22:00
Wednesday 28 January 2015 @ 11:00
Wednesday 28 January 2015 @ 12:00
Wednesday 28 January 2015 @ 16:00
Wednesday 28 January 2015 @ 19:30
但我想要做的是如果日期重复,那么它只显示一次并重复时间,所以例如2015年1月25日星期日将显示为:
Sunday 25 January 2015 @ 12:00 16:00
答案 0 :(得分:1)
您应按日期和加入时间对记录进行分组。
<% if not @film.showings.blank? %>
To book click on a time below:</br>
<% @film.showings.group_by{|showing| showing.show_date.strftime("%A %e %B %Y") }.to_a.each do |showing| %>
<%= showing.first %>@ <%= showing.last.map{|s| s.show_time.strftime("%H:%M")}.join(' ') %><br>
<% end %>
<% else %>
<p>There are currently no showings for this film.</p>
<% end %>
答案 1 :(得分:0)
如果您正在使用它们,可以在助手或装饰器中放置这样的函数。我假设你通过@file.showings
的放映。这将返回一个数组,这是您希望在视图和显示中循环的方式。
def show_times(showings)
showings.each_with_object({}) do |showing, hash|
key = showing.show_date.strftime("%A %e %B %Y")
hash[key] ||= []
hash[key] << showing.show_time.strftime("%H:%M")
end.map do |date, times|
"#{date} @ #{times.join(' ')}"
end
end
答案 2 :(得分:0)
给定一个datetime对象数组,您可以使用以下代码提取日期和时间放映的嵌套哈希。它最好生活在你的电影模型中。
def showings_hash
showings.pluck(:show_time).map {|datetime| datetime.to_date}.uniq.map{|date| {date => dates.select{|datetime| date == datetime.to_date}}}
end
返回:
- 2015-01-12:
- !ruby/object:DateTime 2015-01-12 18:00:00.000000000 Z
- !ruby/object:DateTime 2015-01-12 19:00:00.000000000 Z
- !ruby/object:DateTime 2015-01-12 20:00:00.000000000 Z
- 2015-01-13:
- !ruby/object:DateTime 2015-01-13 20:00:00.000000000 Z
然后您可以在视图中迭代每个显示日期,如下所示:
<% @film.showings_hash.each do |showing_date| %>
<li>
<%= showing_date %>
<% showing_date.each do |showtime| %>
<%= showtime.strftime("%H:%M") %>
<% end %>
</li>
<% end %>