我有以下rake任务自动生成每日帖子,或者如果用户没有帖子,它会自动生成所有帖子追溯到他们的开始日期:
namespace :abc do
desc "Used to generate a new daily log"
task :create_post => :environment do
User.find_each do |currentUser|
starting_date = currentUser.start_date
if Date.today >= starting_date && Date.today.on_weekday?
if currentUser.posts.count.zero?
starting_date.upto(Date.today) { |date| currentUser.generate_post if date.on_weekday? }
else
currentUser.generate_post
end
end
end
puts "It actually worked yo!"
end
end
我试图通过' upto'来实现追溯性的帖子生成。然而,当我运行代码时,我得到以下错误:
NoMethodError: undefined method `upto' for Tue, 09 May 2017 21:42:54 UTC +00:00:Time
C:/Users/vanbeeandr/workspace/online_journal/lib/tasks/create_post.rake:14:in `block (3 levels) in <top (required)>'
C:/Users/vanbeeandr/workspace/online_journal/lib/tasks/create_post.rake:7:in `block (2 levels) in <top (required)>'
NoMethodError: undefined method `upto' for 2017-05-09 21:42:54 UTC:Time
C:/Users/vanbeeandr/workspace/online_journal/lib/tasks/create_post.rake:14:in `block (3 levels) in <top (required)>'
C:/Users/vanbeeandr/workspace/online_journal/lib/tasks/create_post.rake:7:in `block (2 levels) in <top (required)>'
Tasks: TOP => abc:create_post
(See full trace by running task with --trace)
我觉得我的rake任务写得正确所以我不确定为什么会抛出这个错误。任何人都可以帮忙吗?
答案 0 :(得分:0)
实际上,错误表明start_date
是Time
个实例。 Ruby / Rails只允许遍历Date
和DateTime
的实例(参见Iterate over Ruby Time object with delta)。
答案 1 :(得分:0)
我通过在上面的代码中添加.to_datetime来解决这个问题,如下所示:
starting_date = currentUser.start_date.to_datetime