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

问题描述 投票:1回答:1

我正在制作日历,我想要获得本周的第一天,以及本周的最后一天。在尝试这样做时,我在/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

谢谢

ruby-on-rails ruby-on-rails-5
1个回答
2
投票
undefined method `beginning_of_month 'for {: date => Wed, 23 Jan 2019}: Hash

你试图在beginning_of_month上使用Hash方法,而不是在DateTime对象上,检查你的date变量的赋值。

© www.soinside.com 2019 - 2024. All rights reserved.