DEV Community 👩‍💻👨‍💻

Alexander Budchanov
Alexander Budchanov

Posted on • Originally published at jetrockets.pro

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)
Enter fullscreen mode Exit fullscreen mode
user&.company&.name
Enter fullscreen mode Exit fullscreen mode
user && user.company && user.company.name
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

You will receive nil and never been know about this typo.

user&.compppany&.name
=> NoMethodError: undefined method `compppany' for #<User:0x000000123456789>
Enter fullscreen mode Exit fullscreen mode

and

user && user.compppany && user.compppany.name
=> NoMethodError: undefined method `compppany' for #<User:0x000000123456789>
Enter fullscreen mode Exit fullscreen mode

Looks better!

2. If model User has relation company, but company is false. User.new(company: false):

user.try(:company).try(:name)
=> nil
Enter fullscreen mode Exit fullscreen mode
user&.company&.name
=> NoMethodError: undefined method `name' for false:FalseClass
Enter fullscreen mode Exit fullscreen mode

Safe Navigation recognized false. Awesome!

user && user.company && user.company.name
=> false
Enter fullscreen mode Exit fullscreen mode

Hmmm, it does not look like we want.

3. Performance
Read the second part Safe Navigation vs Try in Rails (Part 2: Performance)

Top comments (0)

Regex for lazy developers

regex for lazy devs

You know who you are. Sorry for the callout 😆