0

I have the following rake task which automatically generates a daily post, or if a user has no posts it will generate all the posts automatically retroactively to their start date:

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

I'm attempting to achieve the retroactive generation of posts with the 'upto' method however when I run the code as its written I get the following error:

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)

I feel like my rake task is written correctly so I'm not sure why this error is being thrown. Can anyone help with this?

Andrew
  • 159
  • 2
  • 11

2 Answers2

1

Actually, the error says that start_date is a Time instance. Ruby/Rails only allow to loop through instances of Date and DateTime (see Iterate over Ruby Time object with delta).

Community
  • 1
  • 1
xlts
  • 136
  • 5
  • Hi, this is the migration I used for start_date: "add_column :users, :start_date, :datetime" which I believe set start_date to be of the DateTime class. Do you have any idea why this error is being thrown or how I can get around it? – Andrew May 10 '17 at 00:51
  • Then it also depends on how your database stores datetimes. For your migration, PostgreSQL would create a column of type `TIMESTAMP` and Rails would interpret it as `Time` instance. If your database allowed the `DATETIME` column type then Rails would infer it as calendar-based `DateTime`. – xlts May 10 '17 at 08:04
0

I solved this by adding .to_datetime to my above code as follows:

starting_date = currentUser.start_date.to_datetime
Andrew
  • 159
  • 2
  • 11