如何将布尔值重置为“默认值:false"在一天结束时? [英] How to reset boolean to "default: false" at end of day?
问题描述
我在数据库中有一个布尔值:t.boolean "completed",默认值:false
I have a boolean in the DB: t.boolean "completed", default: false
我ONLY在主页上显示那些仍然false
.
I ONLY show those still false
on the home page.
如果用户勾选一项:
<span class="glyphicon glyphicon-ok"><% :completed %></span>
Completed 变为 true
并因此从主页中消失.
Completed becomes true
and it therefore disappears from the home page.
不过,在每一天结束时,我们如何才能自动将所有内容重置为 default: false
?
At the end of each day though, how can we automatically reset everything back to default: false
?
我是否要创建一个模型方法或范围来执行此操作?
Do I create a model method or scope to do this?
推荐答案
我会使用时间戳而不是布尔值.这有两个好处:
I would use a timestamp instead of a boolean. That has two benefits:
- 您知道用户上次填写的时间
- 您无需在午夜通过 cron 作业重置该值.
步骤如下:首先从数据库中删除 completed
布尔列,然后添加一个 completed_at
时间戳列.
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
这篇关于如何将布尔值重置为“默认值:false"在一天结束时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!