Ruby on Rails group_by (how to group events by month)

人盡茶涼 提交于 2019-12-31 06:17:10

问题


Hey Guys I am new to rails. I have a controller that create events and I want to group them by month (the month of such event date). I am using rails 4 here is my code.

This is my controller

def index
 @events = Event.all
 @event_months = @events.group_by { |t| t.due_at.beginning_of_month }
end

This is my view code

<% @event_months.each do |month, events| %>
  <h2><%= month.strftime('%B') %></h2>
    <% for event in evetns %>
     <div class='event-card'>
      <a href="<%= event.url %>">
       <div class='event-image'>
        <%= image_tag event.image_url(:normal), :class => 'eimage', :style =>  'width:100%;' %>
       </div>
       <div class='event-content'>
        <h1 class='event-title'><%= event.name %></h1>
        <h2 class='event-place'><%= event.where %></h2>
        <h3 class='event-time-date'><%= event.start_time.strftime("%B %d @ %I:%M %p") %></h3>
       </div>
      </a>
     </div>
   <% end %>
 <%= link_to 'Show', event %>
 <%= link_to 'Edit', edit_event_path(event) %>
 <%= link_to 'Destroy', event, method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>

Thank in advance.


回答1:


def index
 @events = Event.all
 @event_months = @events.group_by { |t| t.due_at.month }
end

Month Name in view is given by

Date::MONTHNAMES[month]


来源:https://stackoverflow.com/questions/18862726/ruby-on-rails-group-by-how-to-group-events-by-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!