Safe Navigation vs Try in Rails (Part 1: Basic Differences)
There are some ways of preventing errors like undefined method for nil:NilClass
.
Rails Method
try(...)
Safe Navigation Operator (
&.
)Logical operator
&&
(AND)
Here is how these options look like:
user.try(:company).try(:name)
user&.company&.name
user && user.company && user.company.name
But there are some differences.
1. If model User hasn't relation compppany
(it may be just a typo or renamed model relation/attribute):
user.try(:compppany).try(:name)
=> nil
You will receive nil
and never been know about this typo.
user&.compppany&.name
=> NoMethodError: undefined method `compppany' for #<User:0x000000123456789>
and
user && user.compppany && user.compppany.name
=> NoMethodError: undefined method `compppany' for #<User:0x000000123456789>
Looks better!
2. If model User has relation company, but company is false
. User.new(company: false)
:
user.try(:company).try(:name)
=> nil
user&.company&.name
=> NoMethodError: undefined method `name' for false:FalseClass
Safe Navigation recognized false
. Awesome!
user && user.company && user.company.name
=> false
Hmmm, it does not look like we want.
3. Performance
Read the second part Safe Navigation vs Try in Rails (Part 2: Performance)