Rails Associations, nilClass, try, and Law of Demeter
-
27-10-2019 - |
Question
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.
Solution
You can use delegate, and you end up with my_order.first_name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow