You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopify Script Editor插件undefined method for nil错误修复方法

报错原因

你遇到的undefined method 'end_with?' for nil报错,是因为当customer对象存在,但customer.email为空值(nil)时,直接调用end_with?方法触发了空值调用异常。

修复方案

直接在email和方法之间加Ruby安全导航操作符&.即可,优化后的判断逻辑如下:

if customer && customer.email&.end_with?("@mycompany.com")

逻辑说明:&.会先检查前面的customer.email是否为nil,若为nil会直接返回nil,整个条件判断不成立,自动跳过对应逻辑,不会触发报错。
如果你的Ruby版本不支持安全导航操作符,可以用多层判断的兼容写法:

if customer && customer.email && customer.email.end_with?("@mycompany.com")

额外优化点

你现有代码还存在未定义变量风险:如果没进入if分支,message变量未初始化,后续调用line_item.change_line_price时会报错,建议提前初始化message变量。

完整修改后代码

Input.cart.line_items.each do |line_item|
  next if line_item.variant.product.gift_card?
  discount = 1
  message = nil # 提前初始化message避免未定义报错

  customer = Input.cart.customer
  # 优化后的判断条件
  if customer && customer.email&.end_with?("@mycompany.com")
    message = "Lorem Ipsum"
    discount = 0.2
  end
  next unless discount < 1
  
  line_item.change_line_price(
    line_item.line_price * discount,
    message: message,
  )
end

Output.cart = Input.cart

内容的提问来源于stack exchange,提问作者s_p

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:27:00