簡體   English   中英

使用Ruby On Rails自動生成博客的每日帖子

[英]Automatically Generating Daily Posts For A Blog With Ruby On Rails

目前,我有一個rake任務,我將每天與Heroku Scheduler一起運行。

只要今天的日期在用戶帳戶的“開始日期”之后,當前每天它將在執行rake任務時為用戶生成新帖子。

這是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

我的問題是,如果有人注冊一個帳戶,然后在過去某個時間設置他們的開始日期(這樣他們就可以填寫舊帖子),我當前的rake任務將不會生成回溯的每日帖子。 是否有人對如何解決此問題有任何想法,以使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

在用戶模型中,

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

您的邏輯保持不變,我只是在開始日期到當前日期之間循環,以創建回溯的帖子。 將帖子計數檢查為零將確保該條件僅對於新用戶/較早創建帖子的用戶為真。

希望能幫助到你..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM