From eae99987643bc215863b90e04cdbcdfce9902640 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Wed, 2 Oct 2019 12:55:00 -0500 Subject: [PATCH] Add Update Column Versus Update Attribute as a rails til --- README.md | 3 +- .../update-column-versus-update-attribute.md | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 rails/update-column-versus-update-attribute.md diff --git a/README.md b/README.md index 7a23bdb..2b9382c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_845 TILs and counting..._ +_846 TILs and counting..._ --- @@ -531,6 +531,7 @@ _845 TILs and counting..._ - [Show Rails Models With Pry](rails/show-rails-models-with-pry.md) - [Show Rails Routes With Pry](rails/show-rails-routes-with-pry.md) - [Truncate Almost All Tables](rails/truncate-almost-all-tables.md) +- [Update Column Versus Update Attribute](rails/update-column-versus-update-attribute.md) - [Where Am I In The Partial Iteration?](rails/where-am-i-in-the-partial-iteration.md) ### React diff --git a/rails/update-column-versus-update-attribute.md b/rails/update-column-versus-update-attribute.md new file mode 100644 index 0000000..32d3546 --- /dev/null +++ b/rails/update-column-versus-update-attribute.md @@ -0,0 +1,30 @@ +# Update Column Versus Update Attribute + +Rails offers a whole variety of methods for making updates to the ActiveRecord +objects in your app. Two unique, infrequently-used ones are +[`#update_column`](https://devdocs.io/rails~5.2/activerecord/persistence#method-i-update_column) +and +[`#update_attribute`](https://devdocs.io/rails~5.2/activerecord/persistence#method-i-update_attribute). +What is unique about them is that they are both ways of updating a record while +skipping the validations defined on the model. + +So, how do they differ? + +A call to `#update_attribute` is still going to trigger any callbacks defined +on the model and it will touch the `update_at` column. On the other hand, +`#update_column` can be thought of as a way of directly interacting with the +database -- callbacks are skipped and you are truly only touching the specified +column, `updated_at` is left as is. + +The docs have this recommendation for `#update_attribute`: + +> This is especially useful for boolean flags on existing records. + +And for `#update_column`, they say this: + +> This is the fastest way to update attributes because it goes straight to the +> database, but take into account that in consequence the regular update +> procedures are totally bypassed. + +These are both useful in specific situations, but be sure to know their +differences and to use them with caution.