-
Notifications
You must be signed in to change notification settings - Fork 747
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Get ActiveRecord Attribute Directly From Database as a Rails til
- Loading branch information
1 parent
dc8f1a5
commit 5393195
Showing
2 changed files
with
38 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
36 changes: 36 additions & 0 deletions
36
rails/get-active-record-attribute-directly-from-database.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
# Get ActiveRecord Attribute Directly From Database | ||
|
||
In Rails, an ActiveRecord model will automatically get methods named after each | ||
column in the backing database table. This can be called to retrieve those | ||
values from the respective columns in the database. | ||
|
||
What if you wanted to override and alter one of those values? For example, | ||
ensure the `email` value you're passing around is always fully downcased. | ||
|
||
Something like this won't quite work. | ||
|
||
```ruby | ||
def email | ||
email.downcase | ||
end | ||
``` | ||
|
||
Because the method is named `email`, the `email` reference inside it will call | ||
itself, recursively, until it exceeds the stack. | ||
|
||
Instead, you need a way of referencing the email attribute that is stored in | ||
the database. | ||
[`attribute_in_database`](https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Dirty.html#method-i-attribute_in_database) | ||
will do the trick. | ||
|
||
```ruby | ||
def email | ||
attribute_in_database('email').downcase | ||
end | ||
``` | ||
|
||
That will retrieve the value from the `email` column in the database for this | ||
record, downcase it, and return it. Anyone calling `email` won't notice the | ||
difference. | ||
|
||
h/t [Dillon Hafer](https://twitter.com/dillonhafer) |