我正在开发一个可以与拍卖网站进行比较的应用程序。
"拍卖"有一个固定的结束日期,所以我的问题是,当那个时间发生时,如何将这次拍卖设置为"结束"。
例如
拍卖A:2012年12月25日上午9:00关闭。
如何确保它此时已"关闭"?
我只需使用时间戳以及方法和范围即可。
- 为您的模型添加时间戳,也许可以将其称为
open_until
- 在模型中定义一个
closed?
(也许是open?
)方法,用于根据Time.now
检查时间戳 - 向模型添加
closed
(可能open
)范围。也许将其中一个设置为default_scope
引用
通过此设置,您可以即时检查拍卖是开放还是关闭。
Auction.open.all #=> all open auctions
Auction.closed.all #=> all closed auctions
Auction.first.closed? #=> true if 'open_until' is in the past, false otherwise
Auction.first.open? #=> true if 'open_until' is in the future, false otherwise
如果您使用default_scope
(例如 open
),并且需要找到另一个州的拍卖(例如 closed)
确保调用Auction.unscoped.closed
参考。
当您需要即时关闭拍卖的选项(即无需等待open_until
通过)时,您可以简单地执行以下操作,而无需额外的布尔标志:
def close!
self.update_attribute(:open_until, 1.second.ago)
end
,如果你的Auction
模型上有一个:closed
属性,你想在特定时间设置为 true,你需要运行一个 cron 来定期运行一个 rake 任务来检查新的Auction
是否关闭。
例如,您可以在lib/tasks/close_auctions.rake
中创建一个文件,其中包含以下内容
namespace :myapp do
task "close-auctions" => :environment do
Auctions.where("closes_at < ? and closed = ?", Time.zone.now, false).update_all(closed: true)
end
end
这可以通过运行rake
调用
rake myapp:close-auctions
然后,您可以在 crontab 中的 cron 上运行此 rake 任务。每分钟你都会向crontab添加这样的东西
* * * * * RAILS_ENV=production rake myapp:close-auctions > /dev/null 2>&1
这意味着每分钟,Rails 都会找到任何仍处于打开状态但具有过去新:closes_at
值的Auction
实例,并将这些实例标记为已关闭。