Skip to content

Commit fe8a512

Browse files
committed
Add Set A Timestamp Field To The Current Time as a Rails til
1 parent 667bfbd commit fe8a512

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1018 TILs and counting..._
13+
_1019 TILs and counting..._
1414

1515
---
1616

@@ -668,6 +668,7 @@ _1018 TILs and counting..._
668668
- [Select A Select By Selector](rails/select-a-select-by-selector.md)
669669
- [Select Value For SQL Counts](rails/select-value-for-sql-counts.md)
670670
- [Serialize With fast_jsonapi In A Rails App](rails/serialize-with-fast-jsonapi-in-a-rails-app.md)
671+
- [Set A Timestamp Field To The Current Time](rails/set-a-timestamp-field-to-the-current-time.md)
671672
- [Set default_url_options For Entire Application](rails/set-default-url-options-for-entire-application.md)
672673
- [Set Schema Search Path](rails/set-schema-search-path.md)
673674
- [Show Pending Migrations](rails/show-pending-migrations.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Set A Timestamp Field To The Current Time
2+
3+
To set a timestamp field to the current time, you could reach for the `#update`
4+
method like you would when modifying any other field.
5+
6+
```ruby
7+
MagicLink
8+
.find_by(token: some_token)
9+
.update(used_at: Time.zone.now)
10+
```
11+
12+
This works, but it's more verbose than is necessary and requires that you
13+
construct the right timestamp for _now_ (time zones and all).
14+
15+
Rails has a more concise and idomatic way of doing this:
16+
[`#touch`](https://api.rubyonrails.org/v6.1.0/classes/ActiveRecord/Persistence.html#method-i-touch).
17+
18+
```ruby
19+
MagicLink
20+
.find_by(token: some_token)
21+
.touch(:used_at)
22+
```
23+
24+
Updating a timestamp to the current time is a common action in web
25+
applications, so Rails offers the `#touch` method as a shorthand for doing it.
26+
This will set the given field, in this case `:used_at`, to the current time.
27+
This will also set the `updated_at/on` field.

0 commit comments

Comments
 (0)