在创建后30天内销毁帖子

时间:2014-02-18 20:29:00

标签: ruby-on-rails ruby ruby-on-rails-4

出于学习目的,我创建了一个博客,现在我想在创建后的30天后自动销毁帖子。我怎么能这样做?

这是我的帖子控制器

  def index
    @posts = Post.all
  end
  def create
    @post = current_user.posts.new(post_params)
    @post.save
    redirect_to posts_path
  end
  def destroy
    @post.destroy
     redirect_to posts_path
  end

5 个答案:

答案 0 :(得分:4)

我会设置一个whenever每隔1天运行一次的任务。

生成任务:

rails g task posts delete_30_days_old

然后在创建的文件(lib / tasks / posts.rb)上添加以下代码:

namespace :posts do
  desc "TODO"
  task delete_30_days_old: :environment do
    Post.where(['created_at < ?', 30.days.ago]).destroy_all
  end
end

当然,如果您要删除超过30天的帖子,其他答案可能也可以,但我希望我的数据库包含我将在我的应用程序中使用的干净数据。

答案 1 :(得分:2)

帖子将存储在您的数据库中。该模型与您的数据库进行交互。您的控制器永远不会看到数据库,它只能看到模型显示的内容。如果您想使用控制器内部的模型从数据库中取出,可以使用此代码完成。

@posts = Post.where('created_at >= :thirty_days_ago', thiryty_days_ago: Time.now - 30.days)

此代码中的

Post会调用您继承活动记录的app / model / Post.rb。 .where是主动记录方法,它根据您定义的内容查看数据库。在这里,我们定义了仅提取created_at列中有30天前的时间的行。

如果您查看数据库内部,您会发现created_at列已自动放入其中。

答案 2 :(得分:2)

除了前面提到的whenever gem之外,您还可以使用两个名为SidekiqSidetiq的宝石来安排任务/工作人员。

我一直在工作的大型应用程序上使用它们,我对它非常满意。速度很快(使用Redis,添加了一个简单的宝石,可靠且易于使用)。

# in app/workers/clean_posts.rb
class CleanPosts
  include Sidekiq::Worker
  include Sidetiq::Schedulable

  recurrence { monthly }

  def perform
    # stealing from toolz
    Post.where('created_at >= :thirty_days_ago', thiryty_days_ago: Time.now - 30.days).destroy_all
  end
end

但是,这将从您的数据库中删除帖子,您的应用程序将无法再访问它们。

答案 3 :(得分:1)

要获得所需的结果,您需要更改index这样的操作:

def index
    @posts = Post.where(created_at: 30.days.ago..Time.now)
end

通过这种方式,您不需要销毁帖子,您将获得所需的结果。

如果您需要限制访问旧帖子,则可以使用:

def show
    @post = Post.where(created_at: 30.days.ago..Time.now).find(params[:id])
end

而且,如果我们谈论代码美,那么你应该将where(created_at: 30.days.ago..Time.now)部分移动到模型中的范围,如下所示:

class Post
   ...

   scope :recent, -> { where(created_at: 30.days.ago..Time.now) }
end

并像这样使用它:

Post.recent #=> to get list of recent posts
Post.recent.find(params[:id]) #=> to get recent post with specified id

答案 4 :(得分:0)

您无法从控制器执行此操作,您需要为应用程序添加一些功能。

您需要每天运行一个cron作业,以查找超过30天的帖子并将其销毁。

例如Post.where('created_at < ?', 30.days.ago)

为了更好地处理cron作业,您可以考虑使用帮助很多的whenever gem并在您的应用中保留cron设置。