From 53931955d2d016da9b0697b68266d287fe4086e4 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 28 Mar 2022 10:44:12 -0500 Subject: [PATCH] Add Get ActiveRecord Attribute Directly From Database as a Rails til --- README.md | 3 +- ...record-attribute-directly-from-database.md | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 rails/get-active-record-attribute-directly-from-database.md diff --git a/README.md b/README.md index 13b5c15..022b428 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1189 TILs and counting..._ +_1190 TILs and counting..._ --- @@ -722,6 +722,7 @@ _1189 TILs and counting..._ - [Find Records With Multiple Associated Records](rails/find-records-with-multiple-associated-records.md) - [Force All Users To Sign Out](rails/force-all-users-to-sign-out.md) - [Generating And Executing SQL](rails/generating-and-executing-sql.md) +- [Get ActiveRecord Attribute Directly From Database](rails/get-active-record-attribute-directly-from-database.md) - [Get An Array Of Values From The Database](rails/get-an-array-of-values-from-the-database.md) - [Get An Empty ActiveRecord Relation](rails/get-an-empty-activerecord-relation.md) - [Get The Column Names For A Model](rails/get-the-column-names-for-a-model.md) diff --git a/rails/get-active-record-attribute-directly-from-database.md b/rails/get-active-record-attribute-directly-from-database.md new file mode 100644 index 0000000..ada9f4b --- /dev/null +++ b/rails/get-active-record-attribute-directly-from-database.md @@ -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)