ruby-on-rails - 简化 Rails 中的多个 nil 检查

标签 ruby-on-rails ruby syntax

我应该怎么写:

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

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

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

关于ruby-on-rails - 简化 Rails 中的多个 nil 检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8721949/

相关文章:

ruby-on-rails - 从 SQLite 数据库恢复 PG 本地数据库 - Rails

mysql - 如何确保 SQL 语句被执行,然后才开始下一个代码步骤

ruby-on-rails - ActiveRecord 验证器链接

syntax - Kotlin 默认参数 : forbid zero arguments calls

ruby-on-rails - 如何使用 Devise on Rails 自定义注册?

javascript - 如何在 Backbone View 中访问 Rails 配置信息?

ruby - 在 Ruby 中对数组的一部分进行排序

ruby - 使用 Prawn PDF 跨多个页面的边界框

模板类中模板函数的 C++ 特化

php - 为什么此SQL语句不起作用