mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 23:28:02 +00:00
Add Set A Timestamp Field To The Current Time as a Rails til
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
|
||||
|
||||
_1018 TILs and counting..._
|
||||
_1019 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -668,6 +668,7 @@ _1018 TILs and counting..._
|
||||
- [Select A Select By Selector](rails/select-a-select-by-selector.md)
|
||||
- [Select Value For SQL Counts](rails/select-value-for-sql-counts.md)
|
||||
- [Serialize With fast_jsonapi In A Rails App](rails/serialize-with-fast-jsonapi-in-a-rails-app.md)
|
||||
- [Set A Timestamp Field To The Current Time](rails/set-a-timestamp-field-to-the-current-time.md)
|
||||
- [Set default_url_options For Entire Application](rails/set-default-url-options-for-entire-application.md)
|
||||
- [Set Schema Search Path](rails/set-schema-search-path.md)
|
||||
- [Show Pending Migrations](rails/show-pending-migrations.md)
|
||||
|
||||
27
rails/set-a-timestamp-field-to-the-current-time.md
Normal file
27
rails/set-a-timestamp-field-to-the-current-time.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Set A Timestamp Field To The Current Time
|
||||
|
||||
To set a timestamp field to the current time, you could reach for the `#update`
|
||||
method like you would when modifying any other field.
|
||||
|
||||
```ruby
|
||||
MagicLink
|
||||
.find_by(token: some_token)
|
||||
.update(used_at: Time.zone.now)
|
||||
```
|
||||
|
||||
This works, but it's more verbose than is necessary and requires that you
|
||||
construct the right timestamp for _now_ (time zones and all).
|
||||
|
||||
Rails has a more concise and idomatic way of doing this:
|
||||
[`#touch`](https://api.rubyonrails.org/v6.1.0/classes/ActiveRecord/Persistence.html#method-i-touch).
|
||||
|
||||
```ruby
|
||||
MagicLink
|
||||
.find_by(token: some_token)
|
||||
.touch(:used_at)
|
||||
```
|
||||
|
||||
Updating a timestamp to the current time is a common action in web
|
||||
applications, so Rails offers the `#touch` method as a shorthand for doing it.
|
||||
This will set the given field, in this case `:used_at`, to the current time.
|
||||
This will also set the `updated_at/on` field.
|
||||
Reference in New Issue
Block a user