加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 有没有更好的方法来检查儿童参与?

发布时间:2020-12-17 02:08:04 所属栏目:百科 来源:网络整理
导读:检查items_attributes是否有比下面的代码更好的方法?我必须首先检查params [:order],因为有时可能不存在,但我讨厌长条件的外观. if params[:order] and params[:order][:items_attributes] 更新ruby 2.3,现在你可以使用dig方法了 params.dig(:order,:item_
检查items_attributes是否有比下面的代码更好的方法?我必须首先检查params [:order],因为有时可能不存在,但我讨厌长条件的外观.

if params[:order] and params[:order][:items_attributes]

更新ruby 2.3,现在你可以使用dig方法了

params.dig(:order,:item_attributes)

解决方法

您可以创建辅助方法,以便更轻松地使用嵌套哈希.在lib文件夹中创建ruby_ext.rb文件,并编写以下函数:

module RubyExt
  module SafeHashChain
    def safe(*args)
      if args.size == 0 then self # Called without args ...
      elsif args.size == 1 then self[args[0]] # Reached end
      elsif self[args[0]].is_a?(Hash) then self[args[0]].safe(*args[1..-1])
      else nil end # Reached end-value too soon
    end
  end
end

class Hash; include RubyExt::SafeHashChain; end

在此之后,您可以在嵌套哈希上调用安全方法,如下所示:

params.safe(:order,:items_attributes)

它将从items_attributes返回值.如果order或items_attributes不存在,它将返回nil.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读