I watched a presentation by Sandi Metz nothing a couple of times. I understand that I do nil checks all over the place in my rails projects, but I donβt know how to avoid nil checks and how to do it in an object oriented way when it comes to associations.
Consider the following associations:
#app/models/user.rb class User < ActiveRecord::Base belongs_to :blog end
I grab the user:
@user = User.find(1)
And I want to find his blog:
@user.blog => nil
It returns nil here because this user does not have an associated blog , so the following code would break the application if I did something like this for this user :
@user.blog.title => undefined method `title' for nil:NilClass
A simple fix is ββto do it in a non-object oriented way and just do a nil check (but we want to avoid that because otherwise nil checks are absolutely ubiquitous in the application):
@user.blog.title if @user.blog
Performing zero checks becomes more cumbersome and procedural, the deeper you go through the associations, as shown below:
@user = User.find(1) if @user.blog && @user.blog.hash_tag
What is an object oriented way to avoid nil checking for associations?
I am aware of the rails relay method, although Metz did not seem to recommend the try method. Maybe when it comes to associations on rails: try is the best option?
ruby ruby-on-rails
Neil
source share