It is a memorandum.
If you want to update the record when updating the information in the table, use the update method. However, if you want to update only a specific column, you can't use update. So use update_column.
As a premise, it is assumed that there is an integer type column called users table: post_count that counts the number of posts.
Each time the user posts, the number of posts (= post_count) is added as follows.
sum = current_user.post_count.to_i + 1
current_user.update_column(:post_count, sum.to_i)
To_i is added so that addition can be performed firmly even when the initial value is nil. If the column is nil and it is executed without to_i, the following error will occur.
undefined method `+' for nil:NilClass
By doing to_i, nil can be recognized as the number 0 and can be calculated.
https://qiita.com/lemtosh469/items/371544fa4fd3c333adf1 https://teratail.com/questions/19963
Recommended Posts