Simplify multiple nil checking in Rails

后端 未结 10 1956
一个人的身影
一个人的身影 2020-12-17 06:44

How should I write:

if @parent.child.grand_child.attribute.present?
  do_something

without cumbersome nil checkings to avoid exception:

10条回答
  •  有刺的猬
    2020-12-17 07:28

    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

提交回复
热议问题