Blog Posts

To use delegate or not to ? What other options do we have?

Everyone of us saw that kind of error:

NoMethodError: undefined method `street' for nil:NilClass

That means, we are calling street method on nil value, which in our case is users Address, so it means our user might be homeless :o. To prevent it from happening, we can use, :try, &., delegate and rescue, as we are in ruby/rails. Most people would just use delegate or try and even do not think about other options, so lets do some examples.

Lets create simple model, with one associated record – address.

Here are how we might get our user street:

Chaining methods

eric # the street
bob # NoMethodError

Using try / &.

eric # the street
bob # nil

Using delegate

eric # the street
bob # nil

Using rescue

eric # the street
bob # nil

And finally, SQL way!

eric # the street
bob # nil

I have described all ways of solving nil association problem that I know, I hope that the last one will give you some thinking, if you have any other ways fighting nil, just write a comment!

Thanks for reading, cya next post !