How to reset boolean to “default: false” at end of day?

前端 未结 3 1366
梦如初夏
梦如初夏 2021-01-16 08:41

I have a boolean in the DB: t.boolean \"completed\", default: false

I ONLY show those still false on the home page.<

相关标签:
3条回答
  • 2021-01-16 08:54

    You can create a rake task using whenever gem. Something like below should work

    every 1.day, :at => '12:00 am' do
      runner "YourModel.method_to_update"
    end
    

    And in your model, write a method like below

    def self.method_to_update
      YourModel.update_attribute(completed: false)
    end
    
    0 讨论(0)
  • 2021-01-16 08:55

    I think you will actually want a rake task to reset them all, then just run it once a day with cron. Have a look at the whenever gem.

    You CAN do it without the rake task, but its a bit more difficult and inefficient, you will have to add a completed_timestamp, and set that to the current time whenever it is set to true. Then, whenever you fetch the model, check if the completed_timestamp is before today, and if it is, set it to false before you render your page. You could probably do this in an after_find callback.

    Edit: I highly recommend you go with the cron+rake task solution though, the second method is highly inefficient because you will have to fetch every record and check its timestamp every time you load the page. Its just a terrible solution, but I added it for completeness.

    0 讨论(0)
  • 2021-01-16 09:01

    I would use a timestamp instead of a boolean. That has two benefits:

    1. You know when the user complated the last time
    2. You do not need to reset that value via a cron job at midnight.

    The steps would be: First remove the completed boolean column from your database and add instead a completed_at timestamp column.

    Second add two methods to your model that allow the same behaviour than the boolean column before. That means there is not need to change the controller or views:

    def completed=(boolean)
      self.completed_at = boolean ? Time.current : nil
    end
    
    def completed
      completed_at && completed_at >= Time.current.beginning_of_day
    end
    
    0 讨论(0)
提交回复
热议问题