Simplify multiple nil checking in Rails

后端 未结 10 2004
一个人的身影
一个人的身影 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:37

    Hi Think you can use a flag variable here with rescue option

    flag = @parent.child.grand_child.attribute.present? rescue false
    
    if flag
    do_something
    end
    

提交回复
热议问题