[英]Automatically Generating Daily Posts For A Blog With Ruby On Rails
Currently I have a rake task which I will run daily with the Heroku Scheduler. 目前,我有一个rake任务,我将每天与Heroku Scheduler一起运行。
It currently will generate a new post for the user every day when the rake task is executed as long as today's date is after the "start date" of the users account. 只要今天的日期在用户帐户的“开始日期”之后,当前每天它将在执行rake任务时为用户生成新帖子。
This is the code for the rake task: 这是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
Post.create!(content: "RAKED", user: currentUser, status: "new") if Date.today >= starting_date && Date.today.on_weekday?
end
puts "It worked yo"
end
end
My problem is if someone makes an account then sets their start date sometime in the past (so they can fill in old posts) my current rake task will not generate the backdated daily posts. 我的问题是,如果有人注册一个帐户,然后在过去某个时间设置他们的开始日期(这样他们就可以填写旧帖子),我当前的rake任务将不会生成回溯的每日帖子。 Does anyone have any ideas about how to resolve this so that the rake task still performs its current job but also deals with this case?
是否有人对如何解决此问题有任何想法,以使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
In User model, 在用户模型中,
def generate_post
posts.create!(content: "RAKED", status: "new")
end
Your logic remains the same, I just loopes over the starting date to the current date to create backdated posts. 您的逻辑保持不变,我只是在开始日期到当前日期之间循环,以创建回溯的帖子。 Checking post count to zero will ensure that the condition is true only for the new user/user whose posts are not created earlier.
将帖子计数检查为零将确保该条件仅对于新用户/较早创建帖子的用户为真。
Hope it helps.. 希望能帮助到你..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.