【发布时间】:2015-01-01 11:33:46
【问题描述】:
我目前在我的 Rails 应用程序中有一个 Account 模型,在 AccountsController 的更新操作中,我想检查一个帐户是否在过去 5 分钟内更新。
除非帐户在过去 5 分钟内更新,否则我想执行特定操作。
换句话说,如果帐户在过去 5 分钟内没有更新 -> 运行操作。
我正在努力让下面的代码反映我上面的总结,不幸的是,这取决于我在模型中构造方法的方式(例如,updated_at > 5.minutes.ago 或 updated_at
因此我相信我可能对时间和比较有误解?我需要检查帐户上次更新时间的方法,然后确定从现在开始是否超过 5 分钟。 (例如,6 分钟前、7 分钟前等...)如果超过 5 分钟,则运行该操作!如果不是(例如,4 分钟前、1 分钟前、5 分钟以下的任何内容!),那么不要运行该操作?
我的帐户管理员:
class AccountsController < ApplicationController
def update
respond_to do |format|
if @account.update(account_params)
unless @account.updated_recently?
@account.create_activity :update, owner: current_user, recipient: @account
end
format.html { redirect_to( @account )}
format.json { render json: @account }
else
format.html { redirect_to edit_account_url(@account), flash: {danger: 'Something went wrong, try again.'} }
format.json { render nothing: true }
end
end
end
end
我的账户模型:
class Account < Activerecord::Base
def updated_recently?
updated_at > 5.minutes.ago
end
end
非常感谢
【问题讨论】:
-
如果你调用
@account.update(account_params),它会更新updated_at,然后你立即检查帐户是否为updated_recently?,难怪你会得到这样的行为。 -
哦,当然! - 我可以将其移出“@account.update(account_params)”,但是如果帐户无法更新怎么办?我将有一个运行的操作(因为我的条件现在已满足)但一个尚未更新的帐户 - 有没有办法仅在帐户成功更新时才运行此操作?谢谢
-
您可以在更新前检查它是否最近更新,将其分配给某个局部变量,然后根据该变量的值决定是否应该调用
create_activity。 -
我决定我写的关于这个主题的所有内容都可以作为一个答案。 :)
标签: ruby-on-rails activerecord time