更新rails中的另一个字段以及increment_counter方法



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

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

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

如果您只需要在last_updated_at中设置tiemstamp,您可以使用belongs_to关联中的touch选项来处理订单。类似

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

你可以在这里阅读更多关于

最新更新