我们如何从 date_started
到 Date.current
?
例如,此代码仅计算例程的 date_started
:
routines = current_user.routines.group_by {|i| i.date_started.to_date}
classes << "completed" if routines.include?(day)
但我想制作“已完成”,这是使 td 背景变为蓝色的 CSS 类,按照我在下面解释的方式工作:
架构
create_table "routines", force: true do |t|
t.datetime "date_started"
t.string "action"
t.integer "user_id"
end
我已经关注了这个 tutorial 构建日历。
完整的 calendar_helper.rb
module CalendarHelper
def calendar(date = Date.current, &block)
Calendar.new(self, date, block).table
end
class Calendar < Struct.new(:view, :date, :callback)
HEADER = %w[Sun Mon Tue Wed Thu Fri Sat]
START_DAY = :sunday
delegate :content_tag, :current_user, to: :view
def past
end
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 << "lastmonth" if day.month < date.month
classes << "nextmonth" if day.month > date.month
###
routines = current_user.routines.group_by {|i| i.date_started.to_date}
classes << "completed" if routines.include?(day)
###
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
最佳答案
如果我理解正确,为什么不检查日历中的给定日期是否在您指定的日期范围内?
Controller :
@date_started = Date.today - 2.days
@today = Date.today
@given_date = Date.yesterday
html:
<td class="<%= 'completed' if @given_date >= @date_started and @given_date <= @today %>">
编辑
我想 @given_date
需要是一个数组,这样每一天都可以在您的 HTML 中迭代。如果不了解您如何渲染压延机,就不清楚如何编写它。但总体思路应该可行。
编辑2
HTML 教程是这样的:
<%= calender do |date| %>
<%= date.day %>
# assuming this is where you add your `completed` css class somehow
# check if date.day falls between the @date_started and @today range
<% end %>
编辑3
好的,我现在明白为什么这令人困惑了。我想我明白了。您有许多 routine
对象,并且希望将 routine.date_started
和 Date.today
之间的任何日期突出显示为蓝色。我相信这对你有用:
def day_classes(day)
classes = []
classes << "lastmonth" if day.month < date.month
classes << "nextmonth" if day.month > date.month
###
routines = current_user.routines.group_by {|i| i.date_started.to_date}
# remove this line:
#classes << "completed" if routines.include?(day)
# in favor of this line:
classes << "completed" if routines.any? {|date_attr, routine_obj| day >= date_attr and day <= Date.today }
###
classes.empty? ? nil : classes.join(" ")
end
关于css - 日历:date_started 到 Date.current?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34537825/