mirror of
https://github.com/jbranchaud/til
synced 2026-01-04 23:58:01 +00:00
Add Retrieve An Object If It Exists as a rails til.
This commit is contained in:
@@ -68,6 +68,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
|||||||
- [Conditional Class Selectors in Haml](rails/conditional-class-selectors-in-haml.md)
|
- [Conditional Class Selectors in Haml](rails/conditional-class-selectors-in-haml.md)
|
||||||
- [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md)
|
- [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md)
|
||||||
- [Pretend Generations](rails/pretend-generations.md)
|
- [Pretend Generations](rails/pretend-generations.md)
|
||||||
|
- [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md)
|
||||||
- [Show Pending Migrations](rails/show-pending-migrations.md)
|
- [Show Pending Migrations](rails/show-pending-migrations.md)
|
||||||
|
|
||||||
### ruby
|
### ruby
|
||||||
|
|||||||
19
rails/retrieve-an-object-if-it-exists.md
Normal file
19
rails/retrieve-an-object-if-it-exists.md
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
# Retrieve An Object If It Exists
|
||||||
|
|
||||||
|
Rails' Active Support provides the `blank?` and `present?` convenience
|
||||||
|
methods as extensions to many objects. It also extends the Object class by
|
||||||
|
providing the [`presence`](http://api.rubyonrails.org/classes/Object.html#method-i-presence)
|
||||||
|
method. This method returns the *receiver* if it is not blank, otherwise
|
||||||
|
it returns nil.
|
||||||
|
|
||||||
|
Instead of doing
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
User.nickname.present? ? User.nickname : User.firstname
|
||||||
|
```
|
||||||
|
|
||||||
|
I can simply do
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
User.nickname.presence || User.firstname
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user