问题
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