使用 rails 中的 increment_counter 方法更新另一个字段

Update an another field along with the increment_counter method in rails

我的 Customer 模型上有一个 cache_counter 字段,它是 orders_count。此字段只能使用 increment_counter 方法更新。 Customer.increment_counter(:orders_count, customer_id) 这将增加客户的订单数。我的客户模型中已经有另一个字段 last_updated_at ,我想沿 increment_counter 方法更新此字段。 这怎么可能?

如果您只需要在 last_updated_at 中设置时间戳,您可以使用 belongs_to 关联中的 touch 选项为您的订单设置。像,

class Order < ApplicationRecord
  belongs_to :customer, touch: :last_updated_at
end

您可以阅读更多相关信息here

increment_counter 方法接受第三个可选参数,允许更新时间戳列。因此,您只需将方法调用更改为:

Customer.increment_counter(:orders_count, customer_id, touch: :last_updated_at)