尝试获取一周的第一天时未定义的方法-Rails 5

时间:2019-02-23 19:20:56

标签: ruby-on-rails ruby-on-rails-5

我正在制作日历,正在尝试获取一周的第一天,以及一周的最后一天。尝试执行此操作时,我在/lib/calencar.rb中收到错误消息:

undefined method `beginning_of_month 'for {: date => Wed, 23 Jan 2019}: Hash

这是代码calendar.rb

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

    delegate :content_tag, to: :view

    def table
      content_tag :table, class: "calendar table table-bordered table-striped" 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 << "not-month" if day.month != date.month
      classes.empty? ? nil : classes.join(" ")
    end

    def weeks
      #first = DateTime.strptime(date, "%B %d, %Y")
      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

此外,在index#index控制器中,我有以下代码:

class IndexController < ApplicationController
    helper CalendarHelper
  def index
    @date = params[:date] ? Date.parse(params[:date]) : Date.today
  end
end

谢谢

1 个答案:

答案 0 :(得分:2)

undefined method `beginning_of_month 'for {: date => Wed, 23 Jan 2019}: Hash

您尝试在beginning_of_month对象而不是Hash对象上使用DateTime方法,请检查date变量的分配。