File tree 2 files changed +29
-1
lines changed
2 files changed +29
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://tinyletter.com/jbranchaud ) .
12
12
13
- _ 1018 TILs and counting..._
13
+ _ 1019 TILs and counting..._
14
14
15
15
---
16
16
@@ -668,6 +668,7 @@ _1018 TILs and counting..._
668
668
- [ Select A Select By Selector] ( rails/select-a-select-by-selector.md )
669
669
- [ Select Value For SQL Counts] ( rails/select-value-for-sql-counts.md )
670
670
- [ 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 )
671
672
- [ Set default_url_options For Entire Application] ( rails/set-default-url-options-for-entire-application.md )
672
673
- [ Set Schema Search Path] ( rails/set-schema-search-path.md )
673
674
- [ Show Pending Migrations] ( rails/show-pending-migrations.md )
Original file line number Diff line number Diff line change
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.
You can’t perform that action at this time.
0 commit comments