Use the Rails Try Method to Get an Attribute if Object is not nil
This is a very simple and powerful technique that many Rails programmers are not aware of. Thus, most people tend to use a more verbal form of an expression that can be formed in a much better and concise manner. It’s quite typical and you can in fact see it quite a lot in Rails code. It goes like this :
unless user.clan_membership.nil? user.clan_membership.role end
This code is aiming to get a user clan_membership and discover what role this user has in their clan. The problem is that if the user does not have a clan, user.clan_membership will be nil and therefore executing something like ‘nil.role’ will raise a Rails nil object exception. Thus, many new Rails programmers tend to use a nil? check and only then get the user role.
However, this is not the best way to do things. There is a Rails method, named try, that will help you a lot in such situations. The idea behind try is that it only tries to get the attribute value if the caller object is not nil. Therefore, you could write :
If the user does have a clan_membership, it will return the user role. If not, it will just return nil and save you from all the nil exception hassle. It’s a very handy technique, so it would be nice to use it whenever it applies to your applications.