Mar 03

Since Rails 2.3 released, a new try method was introduced. This new handy method allows you to invoke a method on a object without having to worry a NoMethodError exception will be raised. If the receiving object is a nil object then nil will be returned.

For example, there is no user with login “wolfman” so user.email will raise NoMethodError

user = User.find_by_login("wolfman")
user.email

You can avoid NoMethodError using try

user = User.find_by_login("wolfman")
user.try(:email)

More documentation on try.

Leave a Reply

Security Code: