Automatically change status of post Rails

孤人 提交于 2019-12-07 08:14:14

问题


In my rails application I have a job model which I want the status to be changed automatically to "archived" after 30 days from approval by the admin is this possible? if so what is the way to do it?


回答1:


I would add an attribute named "archive_time" as a datetime when it enters the approved state. Then you can set up a rake task to set the archived state and where the archive_time is in the past. This might look like this:

jobs = Job.where("state = ? and archive_time >= ?", 'approved', Time.now)
jobs.each {|job| job.archive }

Then schedule the rake task to be run once a day. I would use cron to achieve this.




回答2:


A rake task or background job (such as Active Job or Delayed Job ) can do the trick however you might not need them in this case. If you are dealing with timestamps in your database, you can create a scope or a method to mark jobs as archived.

For instance, if you have a column named approved_at that is a datetime. When you approve a job, you set the approved_at = Time.now.

Now you can create a method that indicates if the job is archived:

def is_archived?
  approved_at && approved_at < Time.now - 30.days
end

And to get all the archived jobs, you can create a scope:

scope :archived, -> { where('approved_at IS NOT NULL AND approved_at <?', Time.now - 30.days)}


来源:https://stackoverflow.com/questions/30132217/automatically-change-status-of-post-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!