【问题标题】:Using the Ruby on Rails 'upto' method in a Rake task在 Rake 任务中使用 Ruby on Rails 'upto' 方法
【发布时间】:2017-05-09 21:53:56
【问题描述】:

我有以下自动生成每日帖子的 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 任务写得正确,所以我不确定为什么会抛出这个错误。有人可以帮忙吗?

【问题讨论】:

  • 用户的start_date 是哪个类的实例?是日期、日期时间...?
  • start_date 是日期时间

标签: ruby-on-rails


【解决方案1】:

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

【讨论】:

  • 嗨,这是我用于 start_date 的迁移:“add_column :users, :start_date, :datetime” 我相信它将 start_date 设置为 DateTime 类。你知道为什么会抛出这个错误或者我该如何解决它吗?
  • 那么它还取决于您的数据库如何存储日期时间。对于您的迁移,PostgreSQL 将创建一个 TIMESTAMP 类型的列,Rails 会将其解释为 Time 实例。如果您的数据库允许 DATETIME 列类型,那么 Rails 会推断它是基于日历的 DateTime
【解决方案2】:

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

starting_date = currentUser.start_date.to_datetime

【讨论】:

    猜你喜欢
    • 2011-02-09
    • 2015-03-10
    • 1970-01-01
    • 2011-03-04
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多