Skip to content

Commit 5393195

Browse files
committed
Add Get ActiveRecord Attribute Directly From Database as a Rails til
1 parent dc8f1a5 commit 5393195

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
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://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1189 TILs and counting..._
13+
_1190 TILs and counting..._
1414

1515
---
1616

@@ -722,6 +722,7 @@ _1189 TILs and counting..._
722722
- [Find Records With Multiple Associated Records](rails/find-records-with-multiple-associated-records.md)
723723
- [Force All Users To Sign Out](rails/force-all-users-to-sign-out.md)
724724
- [Generating And Executing SQL](rails/generating-and-executing-sql.md)
725+
- [Get ActiveRecord Attribute Directly From Database](rails/get-active-record-attribute-directly-from-database.md)
725726
- [Get An Array Of Values From The Database](rails/get-an-array-of-values-from-the-database.md)
726727
- [Get An Empty ActiveRecord Relation](rails/get-an-empty-activerecord-relation.md)
727728
- [Get The Column Names For A Model](rails/get-the-column-names-for-a-model.md)
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Get ActiveRecord Attribute Directly From Database
2+
3+
In Rails, an ActiveRecord model will automatically get methods named after each
4+
column in the backing database table. This can be called to retrieve those
5+
values from the respective columns in the database.
6+
7+
What if you wanted to override and alter one of those values? For example,
8+
ensure the `email` value you're passing around is always fully downcased.
9+
10+
Something like this won't quite work.
11+
12+
```ruby
13+
def email
14+
email.downcase
15+
end
16+
```
17+
18+
Because the method is named `email`, the `email` reference inside it will call
19+
itself, recursively, until it exceeds the stack.
20+
21+
Instead, you need a way of referencing the email attribute that is stored in
22+
the database.
23+
[`attribute_in_database`](https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Dirty.html#method-i-attribute_in_database)
24+
will do the trick.
25+
26+
```ruby
27+
def email
28+
attribute_in_database('email').downcase
29+
end
30+
```
31+
32+
That will retrieve the value from the `email` column in the database for this
33+
record, downcase it, and return it. Anyone calling `email` won't notice the
34+
difference.
35+
36+
h/t [Dillon Hafer](https://twitter.com/dillonhafer)

0 commit comments

Comments
 (0)