如何从NetSuite哈希自定义字段中提取attributes的value值?
NetSuite自定义字段哈希提取value值报错解决
问题场景
给定NetSuite自定义字段的哈希结构如下:
"custbody_delivery_ticket_number" => { "script_id" => "custbody_delivery_ticket_number", "internal_id" => "2701", "type" => "platformCore:DateCustomFieldRef", "attributes" => { "value" => "123abc" } }
尝试用以下代码提取attributes内的value值:
delivery_ticket_number: "#{netsuite_sales_orders.custom_field_list.custom_fields.select['custbody_nef_meter_ticket_number']['attributes']['value']}",
抛出错误:
NoMethodError: undefined method `[]' for #Enumerator:0x00005589ec778730
错误原因
select方法未传入块参数时,会返回一个Enumerator对象,而非预期的哈希结果,因此无法通过[]进行键值访问。
解决方案
根据custom_fields的实际数据类型,选择以下两种方式之一:
情况1:custom_fields是哈希结构
如果custom_fields本身是以script_id为键的哈希,直接通过键名访问即可:
delivery_ticket_number: netsuite_sales_orders.custom_field_list.custom_fields['custbody_nef_meter_ticket_number']&.dig('attributes', 'value')
使用&.dig可避免字段不存在时抛出NilError,同时安全完成嵌套值提取。
情况2:custom_fields是数组结构
如果custom_fields是包含多个字段对象的数组,先用find方法定位目标字段再提取值:
field = netsuite_sales_orders.custom_field_list.custom_fields.find { |f| f['script_id'] == 'custbody_nef_meter_ticket_number' } delivery_ticket_number: field&.dig('attributes', 'value')
验证提示
确认custbody_nef_meter_ticket_number与哈希示例中的custbody_delivery_ticket_number是否为同一字段(注意标识符拼写一致性),避免因字段名错误导致匹配失败。
内容的提问来源于stack exchange,提问作者Paul Anthony McGowan
相关产品推荐
相关产品推荐

