Today I Learned

This project exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any Rocketeer as well as selected friends of JetRockets. We hope you enjoy learning along with us.

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)

Looking for help? JetRockets has been an leader in Ruby on Rails since 2012. Rails is a core skill for each developer at JetRockets and we'd love to take a look at your project. Contact us and find out how we can help you.