2014-11-05 114 views
0

我目前有一个帐户模型在我的rails应用程序,在AccountsController的更新操作内我想检查一个帐户是否已在最近5分钟内更新。rails updated_at之间的时间现在和时间5分钟前

除非帐户在最近5分钟内更新,否则我想运行特定操作。

换句话说,如果账户在最近5分钟内没有更新 - >执行操作。

Im努力得到下面的代码来反映我上面的总结,不幸取决于我在我的模型中构造方法的方式(例如,updated_at> 5.minutes.ago或updated_at < 5.minutes.ago)它或者始终运行该操作或从不运行该操作。

因此,我相信我可能会对时间和比较有误解吗?我需要使用该方法来检查上次更新帐户的时间,然后决定是否从现在开始超过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更新,紧接着又发生

+0

如果您调用'@ account.update(account_params)',它会更新'updated_at',并且之后立即检查账户是否是'updated_recently?',这就难怪你会得到这样的行为。 – 2014-11-05 10:12:48

+0

哦,当然是! - 我可以将其移出“@ account.update(account_params)”,但如果帐户无法更新?我将执行一个可以运行的操作(因为我的条件已满足),但是没有更新的帐户 - 只有当帐户成功更新时才有这种运行方式吗?谢谢 – drac 2014-11-05 10:21:28

+0

您可以在更新之前检查它是否最近更新,将其分配给某个局部变量,然后根据此变量的值决定是否应调用'create_activity'。 – 2014-11-05 10:27:27

回答

1

你的错误您检查帐户是否为updated_recently?。为了避免这种情况,你可以检查它是否被更新之前最近更新的,把它分配给了一些局部变量,那么这个变量的值决定的基础上,如果你要调用create_activity,这样的事情:

updated_recently = @account.updated_recently? 
if @account.update(account_params) 
    unless updated_recently 
    @account.create_activity :update, owner: current_user, recipient: @account 
    end 
    # ... 
end 
+0

我明白了,谢谢你的帮助 – drac 2014-11-05 10:32:35