由于定义了这样一条路线,我可以访问数周:

get 'missions/:year/:week' => 'missions#index'

我想显示一周和两个链接,以转到前一周和下一周。
我们需要知道下个星期是哪一年。周给了我正确的周数,但我需要知道年份。
看来下个星期四的新年是可行的,但这有点难看。以下是我在“任务索引”操作中的操作,这样我就可以拥有正确的URL:
@week = params[:week]
@year = params[:year]

@start_date = Date.commercial(@year.to_i, @week.to_i)

# To navigate between weeks
@prev_week = (@start_date - 1.week).cweek
@prev_year = (@start_date - 1.week + 4.days).year

@next_week = (@start_date + 1.week).cweek
@next_year = (@start_date + 1.week + 4.days).year

你知道怎么做得更好吗?

最佳答案

Date#cweek返回的周数的正确年份由Date#cwyear返回。因此,此方法使其成为与cweek一起使用的主要候选方法。

# To navigate between weeks
@prev_week = (@start_date - 1.week).cweek
@prev_year = (@start_date - 1.week).cwyear

@next_week = (@start_date + 1.week).cweek
@next_year = (@start_date + 1.week).cwyear

关于ruby-on-rails - 如何遍历数年和数周,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24576981/

10-10 12:40