針對 db 的數值欄位做直接加減以避免 inconsistent update 問題 即想在 sql 中實作出
1
| |
rails 在實作 counter cache 中有 api 可用
1
| |
對應 sql:
1
| |
參考
http://apidock.com/rails/ActiveRecord/CounterCache/increment_counter
當然, 遞減的 method 相對是 decrement_counter
若增減值大於 1 的話, 則可用 update_counters 來實作
1
| |
輸出 sql
1
| |
update_counters 可以一次對多個欄位做增減
1
| |
參考
http://apidock.com/rails/ActiveRecord/CounterCache/update_counters