0

我有一个简单的脚手架“帖子”,现在我想为其添加调度,以便我可以创建一个帖子并为其添加日期,而帖子只会在那时被创建(实际发布)。

我可以看到我需要为 cron 使用“无论何时”gem,并且可能想使用 published_at 字段,但我有点困惑如何做到这一点?

谢谢

4

2 回答 2

3

我认为最好只添加一个 published_at 字段,因为您实际上已经在那里有了记录。

# Add columns. (DB migration)
add_column :posts, :draft, :boolean, :default => true
add_column :posts, :published_at, :datetime

# Define scopes. (model)
#
# These set up shortcuts that will allow you to do:
#   Post.draft
# instead of this in many places:
#   Post.where(:draft => true)
# Or:
#   Post.published
# instead of:
#   Post.where(:draft => false).where('published_at <= ?', Time.zone.now)
scope :draft, where(:draft => true)
scope :published, proc {
  where(:draft => false).where('published_at <= ?', Time.zone.now)
}

# If the user does not set published_at but sets post to public, automatically
# set published_at to the current time before persisting the record to the
# DB. (model)
before_save :ensure_published_at, :unless => :draft?
protected
def ensure_published_at
  # Set it to current time if none has been specified.
  self.published_at ||= Time.zone.now
end

# Might be helpful if you have a "Publish" action. (model)
#
# This already sets draft to false and published at to the default (because of
# ensure_published_at above:
#   post.publish!
def publish!
  self.draft = false
  self.save!
end

# Finally, fetch the published posts: (controller action)
# It's best to also add pagination and ordering.
@posts = Post.published
于 2013-02-19T05:06:33.597 回答
2

我可以向您展示在我的一个项目中实际工作的代码,例如:

# config/schedule.rb:
#  Once wheneverifyed - asks cron to call rake task `posts:publish` every minute.
#  See whenever docs at https://github.com/javan/whenever.
every 1.minute do
  rake 'posts:publish', environment: environment
end

# models/post.rb
class Post < ActiveRecord::Base

  # Every post has
  #  status - either PUBLISH_WAITING or PUBLISHED
  #  publish_at - date/time post need to be published
  #  published_at - actual time post was published (in this example it'll always be equal to publish_at)

  PUBLISH_WAITING, PUBLISHED = 'not_published', 'published'

  scope :publish_waiting, where(status: Post::PUBLISH_WAITING)
  scope :ready_for_publish, where('publish_at <= ?', Time.now)

  # Method to make post published!
  # Warn: it doesnt check if it is time to publish! Just do that.
  def publish_now!
    self.status = Post::PUBLISHED
    self.published_at = self.publish_at
    save!
  end
end

# lib/tasks/posts.rake
#  Define rake `posts:publish` task,
#  which when called searches through all not published
#  (but ready to be published) posts and publishes them.
#  You can call that task manually from CLI `$ rake posts:publish` to check.
namespace :posts do
  desc "Publish posts with cron on certain time"
  task :publish => :environment do
    Post.publish_waiting.ready_for_publish.find_each do |post|
      post.publish_now!
    end
  end
end
于 2013-02-19T05:09:00.637 回答