通过更新增加模型属性!方法

Increment model attribute with update! method

在我的应用程序中,当用户未通过法律测试时,我应该将他们的状态更改为 inactive,当前日期更改为 status_updated_at 并递增 failed_attempts。通常我会使用类似的东西:

  current_user.update!(
    status: 'inactive',
    failed_attempts: +1,
    status_updated_at: Date.current
    )

但是有没有语法可以使用像 increment 这样的内置方法成为 current_user.update!( ... ,increment!(:failed_attempts)...),

我不知道,但使用 counter_cache 可能有点矫枉过正,因为用户只有 2 到 5 次尝试。

我认为这不是一蹴而就的可能性。您可以尝试这样做:

current_user.increment(:failed_attempts)
current_user.update_attributes(status: 'inactive', status_updated_at: Date.current)
current_user.save!

或者这个:

current_user.update!(
  status: 'inactive',
  failed_attempts: (current_user.failed_attempts || 0) + 1,
  status_updated_at: Date.current
)

可能存在竞争条件(即模型实例持有与数据库中的值相比过时的值),因此可以将 update_counterstransaction:

一起使用
transaction do
  current_user.class.update_counters(current_user.id, failed_attempts: 1)
  current_user.update(status: :inactive, status_updated_at: Date.current)
end