Simplify multiple nil checking in Rails

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

    You coult just catch the exception:

    begin
      do something with parent.child.grand_child.attribute
    rescue NoMethodError => e
      do something else
    end
    

提交回复
热议问题