How should I write:
if @parent.child.grand_child.attribute.present?
do_something
without cumbersome nil checkings to avoid exception:
All these answers are old, so I thought I should share more modern options.
If you are getting an association that might not exist:
@parent&.child&.grand_child&.attribute
if you are reaching into a hash for a key that might not exist:
hash = {
parent_key: {
some_other_key: 'a value of some sort'
},
different_parent_key: {
child_key: {
grand_child: {
attribute: 'thing'
}
}
}
}
hash.dig(:parent_key, :child_key, :grandchild_key)
Either of these will gracefully return nil if child, grandchild, or attribute don't exist