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

时间:2017-06-28 20:04:10

标签: ruby-on-rails ruby shopify

我目前有一个有效的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

当我插入 not yesdiscount的代码时,即使我检查代码是否与批准的代码不相符,折扣仍然适用。

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

1 个答案:

答案 0 :(得分:1)

您的案例语法不正确,案例使用如下:

# 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