使用Ruby on Rails' upto' Rake任务中的方法

时间:2017-05-09 21:53:57

标签: ruby-on-rails

我有以下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任务写得正确所以我不确定为什么会抛出这个错误。任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

实际上,错误表明start_dateTime个实例。 Ruby / Rails只允许遍历DateDateTime的实例(参见Iterate over Ruby Time object with delta)。

答案 1 :(得分:0)

我通过在上面的代码中添加.to_datetime来解决这个问题,如下所示:

starting_date = currentUser.start_date.to_datetime