Non-tech founder’s guide to choosing the right software development partner Download Ebook
Home>Blog>Safe navigation vs try in rails (part 1: basic differences)

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)

Discover More Reads

Recent Projects

We take pride in creating applications that drive growth and evolution, from niche startups to international companies.

Do you have a tech idea?

Let’s talk!

By submitting this form, you agree with JetRockets’ Privacy Policy

If you prefer email, write to us at hello@jetrockets.com