Simplify multiple nil checking in Rails

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

    If the attribute you are checking is always the same, create a method in @parent.

    def attribute_present?
      @parent.child.present? && @parent.child.grandchild.present? && @parent.child.grandchild.attribute.present?
    

    end

    Alternatively, create has_many :through relationship so that @parent can get to grandchild so that you can use :

    @parent.grandchild.try(:attribute).try(:present?)
    

    Note: present? is not just for nil, it also checks for blank values, ''. You can just do @parent.grandchild.attribute if it's just nil checking

提交回复
热议问题