【问题标题】:rails updated_at between time now and time 5 minutes agorails updated_at 从现在到 5 分钟前的时间
【发布时间】: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


【解决方案1】:

您的错误发生是因为您调用@account.update(account_params),它会更新updated_at,然后您立即检查帐户是否为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

【讨论】:

    【解决方案2】:

    updated_recently = @account.updated_recently? 如果@account.update(account_params) 除非updated_recently @account.create_activity:更新,所有者:current_user,收件人:@account 结束

    【讨论】:

    • 为答案添加更多上下文和解释可能会很棒。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 2012-08-14
    • 2014-01-26
    • 1970-01-01
    • 2017-05-26
    • 2020-07-30
    • 1970-01-01
    相关资源
    最近更新 更多