0

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

我认为,问题在于我使用datetime而不是dateRyan 在他的演员阵容中使用的那样。但我无法理解如何仅从我的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>

谢谢你的帮助!

4

1 回答 1

3

我在这里找到了答案

解决方案是仅将事件分组date,而不是datetime

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

Joe Frambach 有一个正确的想法。

于 2013-06-07T20:17:17.957 回答