简化 Rails 中的多个 nil 检查 [英] Simplify multiple nil checking in Rails

查看:30
本文介绍了简化 Rails 中的多个 nil 检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该怎么写:

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

没有繁琐的 nil 检查以避免异常:

without cumbersome nil checkings to avoid exception:

if @parent.child.present? && @parent.child.grandchild.present? && @parent.child.grandchild.attribute.present?

谢谢.

推荐答案

Rails 有 object.try(:method):

if @parent.try(:child).try(:grand_child).try(:attribute).present?
   do_something

http://api.rubyonrails.org/classes/Object.html#method-i-try

这篇关于简化 Rails 中的多个 nil 检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆