事件不会显示在日历中

时间:2013-06-06 21:04:22

标签: ruby-on-rails ruby-on-rails-3 date datetime calendar

我已按照Railscast #213创建了日历,其中显示了current_user.events。但是我的日历没有显示它们。

我认为,这个问题是因为我使用的是datetime而不是date,就像Ryan在演员阵容中使用的那样。但我无法理解如何仅从我的datetime解析日期。

我尝试将@date变量更改为

@date = params[:datetime] ? DateTime.parse(params[:datetime]).to_date : Date.today

而不是

@date = params[:date] ? Date.parse(params[:date]) : Date.today

用于演员阵容,但没有帮助。

所以,我的events_controller#index是:

def index
  @events = current_user.events.all
  @events_by_date = @events.group_by(&:start_date)
  @event = Event.new(params[:event])
  @date = params[:datetime] ? DateTime.parse(params[:datetime]).to_date : Date.today
end

日历助手和events#index我没有改变就离开了。

calendar_helper.rb

module CalendarHelper
  def calendar(date = Date.today, &block)
    Calendar.new(self, date, block).table
  end

  class Calendar < Struct.new(:view, :date, :callback)
    HEADER = %w[Monday Tuesday Wednesday Thursday Friday Saturday Sunday]
    START_DAY = :monday

    delegate :content_tag, to: :view

    def table
      content_tag :table, class: 'calendar' do
        header + week_rows
      end
    end

    def header
      content_tag :tr do
        HEADER.map { |day| content_tag :th, day }.join.html_safe
      end
    end

    def week_rows
      weeks.map do |week|
        content_tag :tr do
          week.map { |day| day_cell(day) }.join.html_safe
        end
      end.join.html_safe
    end

    def day_cell(day)
      content_tag :td, view.capture(day, &callback), class: day_classes(day)
    end

    def day_classes(day)
      classes = []
      classes << 'today' if day == Date.today
      classes << 'notmonth' if day.month != date.month
      classes.empty? ? nil : classes.join(' ')
    end

    def weeks
      first = date.beginning_of_month.beginning_of_week(START_DAY)
      last = date.end_of_month.end_of_week(START_DAY)
      (first..last).to_a.in_groups_of(7)
    end
  end
end

index.html.erb

<div id="events">
  <h2 id="month">
    <%= link_to "<", date: @date.prev_month %>
    <%= @date.strftime("%B %Y") %>
    <%= link_to ">", date: @date.next_month %>
  </h2>
  <%= calendar @date do |date| %>
      <%= date.day %>
      <% if @events_by_date[date] %>
          <ul>
            <% @events_by_date[date].each do |event| %>
                <li><%= link_to event.name, event %></li>
            <% end %>
          </ul>
      <% end %>
  <% end %>
</div>

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

我找到了答案here

解决方案是仅按date对事件进行分组,而不是datetime

@events_by_date = @events.group_by { |i| i.start_date.to_date }

Joe Frambach有一个正确的想法。