Shopify/Ruby - 阻止使用折扣,除非它是特定的单数代码

Shopify/Ruby - prevent a discount from being used unless it's a specific singular code

我目前有一个有效的 Shopify/Ruby 脚本可以在购物车中有特定产品时阻止折扣代码。它看起来像这样:

productid = 1234567890

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  puts product.id
  next if product.gift_card?
  next unless product.id == productid
  case Input.cart.discount_code
  when CartDiscount::Percentage
    Input.cart.discount_code.reject({message: "Cannot be used with This Product"})
  when CartDiscount::FixedAmount
    Input.cart.discount_code.reject({message: "Cannot be used with this product"})
  when CartDiscount::Shipping
    Input.cart.discount_code.reject({message: "Cannot be used with this product"})
  end
end

Output.cart = Input.cart

我现在想将其更改为仍然拒绝在该给定产品上使用折扣代码,但如果使用了非常具体的折扣代码则允许使用。我尝试了以下两种方法:

1:

productid = 1234567890

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  puts product.id
  next if product.gift_card?
  next unless product.id == ma770id
  case Input.cart.discount_code
  when cart.discount_code != 'yesdiscount'
    Input.cart.discount_code.reject({message: "Cannot be used with this product"})
  end
end


Output.cart = Input.cart

2:

productid = 1234567890

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  puts product.id
  next if product.gift_card?
  next unless product.id == productid
  case Input.cart.discount_code != 'yesdiscount'
  when CartDiscount::Percentage
    Input.cart.discount_code.reject({message: "Cannot be used with This Product"})
  when CartDiscount::FixedAmount
    Input.cart.discount_code.reject({message: "Cannot be used with this product"})
  when CartDiscount::Shipping
    Input.cart.discount_code.reject({message: "Cannot be used with this product"})
  end
end

Output.cart = Input.cart

当我插入一个 不是 yesdiscount 的代码时,折扣仍然适用,即使我检查代码是否不等于批准的代码.

我的第一个想法是语法,但已经确认不等于运算符实际上是!=。这里逻辑上发生了什么导致接受折扣,即使我正在检查它不是我想要工作的那个?

您的大小写语法不正确,大小写用法如下:

# a is variable, if a contains val1 it goes to first when, if val2 it goes to second when, if neithr it goes to else
case a
when 'val1'
when 'val2'
else
end

列出了其他使用案例的方法here

对第一种方法应用正确的大小写语法:

productid = 1234567890

Input.cart.line_items.each do |line_item|
 product = line_item.variant.product
 puts product.id
 next if product.gift_card?
 next unless product.id == ma770id
 case Input.cart.discount_code
 when 'yesdiscount'
      #code here if yesdiscount is discount_code
 else 
  Input.cart.discount_code.reject({message: "Cannot be used with this product"})
 end
end