1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Update Column Versus Update Attribute as a rails til

This commit is contained in:
jbranchaud
2019-10-02 12:55:00 -05:00
parent ef1d4d3519
commit eae9998764
2 changed files with 32 additions and 1 deletions

View File

@@ -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

View File

@@ -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.