pages_controller.rb
@past_challenges_by_years = @past_challenges.group_by { |t| [t.deadline.year, t.deadline.month] }
How can I break it down in the view with year and then subdivide it with month like this:
2014 # Years
01 # Months
Challenge
Challenge
02
Challenge
08
Challenge
2016
03
Challenge
08
Challenge
view.html.erb
<% @past_challenges_by_years.sort.each do |year, challenges| %>
<%= year %>
<%= month %> # I don't know how to define this.
<% for challenge in challenges %>
etc...
<% end %>
<% end %>
I would start by sorting the keys and then look up the challenges while iterating through those keys.
<% @past_challenges_by_years.keys.sort.each do |(year, month)| %>
<%= year %>
<br />
<%= month %>
<br />
<% @past_challenges_by_years[[year, month]].each do |challenge| %>
<%= challenge %>
<br />
Edit: Here is a new solution that only displays years and months once.
@past_challenges_by_years.keys.map { |a| a[0] }.uniq.sort.each do |year|
puts year
@past_challenges_by_years.keys.select { |a| a[0] == year }.map { |a| a[1] }.uniq.sort.each do |month|
puts month
@past_challenges_by_years[[year, month]].each do |challenge|
puts challenge
end
end
end
I think it should be simple enough to convert to ERB.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.