2017-05-08 106 views
0

目前我有一个rake任务,我将使用Heroku Scheduler每日运行一次。使用Ruby On Rails自动生成日志文章使用Ruby On Rails

只要今天的日期在用户帐户的“开始日期”之后,它现在每天都会为用户生成一个新的帖子。

这是耙任务的代码:

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 

Post.create!(content: "RAKED", user: currentUser, status: "new") if Date.today >= starting_date && Date.today.on_weekday? 
end 

puts "It worked yo"  
end 

end 

我的问题是,如果有人让一个帐户,然后一段时间设定开始日期的过去(这样他们就可以在旧帖子填写)我目前的耙子任务将不会生成每日回帖。有没有人有任何关于如何解决这个问题,使耙子任务仍然执行其当前的工作,但也处理这种情况?

回答

0
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 

在用户模式,

def generate_post 
    posts.create!(content: "RAKED", status: "new") 
end 

你的逻辑是一样的,我只是loopes在起始日期为当前日期创建追溯职位。检查过帐数量为零将确保条件为真,仅适用于其以前未创建帖子的新用户/用户。

希望它有帮助..

+0

谢谢,这是一个很好的答案! – Andrew

+0

我很高兴它帮助..我会建议你改变主题/问题是更一般的。就像你所面对的回溯或类似错误......问题实际上并不是“如何自动生成日常帖子”,而是不同。 –

+0

嗨,只是一个后续行动:我试图实现这一点,我得到以下错误:NoMethodError:未定义的方法'upto' – Andrew