Rails Associations, nilClass, try, and Law of Demeter

159 Views Asked by At

So I never know what to do here.

Say you have Order, which has_one Member.

If you call say, my_order.member.first_name where that associated member has been deleted, you can a nilClass error. I can do my_order.member.try(:first_name).. but that just seems like a dumb workaround. I don't want to stick a bunch of tries everywhere.

I've read [this article] on Nil objects: http://robots.thoughtbot.com/post/8181879506/if-you-gaze-into-nil-nil-gazes-also-into-you?

Good stuff. But I would think rails has something handy for this since it's so common.. instead of writing your own custom nilClass or something.

1

There are 1 best solutions below

0
On BEST ANSWER

You can use delegate, and you end up with my_order.first_name