首页 > 解决方案 > 使用 shopify_api 从变体对象获取价格 - 和 ruby​​ on rails

问题描述

我正在使用 shopify_api ( https://github.com/Shopify/shopify_api ) 为使用 Ruby 的 Shopify 创建应用程序。

对于 a Base::Product,通过直接调用product.variants,我将拥有:

[#<ShopifyAPI: :Variant: 0x00007fa15cb0e960 @attributes={
"id"=>12664776392816,
"title"=>"Default Title",
"price"=>"5.00",
"sku"=>"",
"position"=>1,
"inventory_policy"=>"deny",
"compare_at_price"=>nil,
"fulfillment_service"=>"manual",
"inventory_management"=>nil,
"option1"=>"Default Title",
"option2"=>nil,
"option3"=>nil,
"created_at"=>"2018-08-27T03:17:24-04:00",
"updated_at"=>"2019-04-07T23:52:00-04:00",
"taxable"=>true,
"barcode"=>"",
"grams"=>0,
"image_id"=>nil,
"weight"=>0.0,
"weight_unit"=>"kg",
"inventory_item_id"=>12758757474416,
"inventory_quantity"=>0,
"old_inventory_quantity"=>0,
"requires_shipping"=>true,
"admin_graphql_api_id"=>"gid://shopify/ProductVariant/12664776392816"
}, @prefix_options={
:product_id=>1389200408688
}, @persisted=true>
]

在这种情况下,我如何直接price从这个返回的json中获取属性

编辑:我只是在中间的轨道上跳进红宝石,所以这是我迄今为止尝试过的:

product.variants.prices--> 在我看来,它肯定是行不通的,但不妨尝试用undefined method价格返回#`

解析 JSON

1)JSON.parse(product.varient)['price'] 返回 no implicit conversion of Array into String

2)variant = ActiveSupport::JSON.decode(product.variants[0])variant = ActiveSupport::JSON.decode(product.variants)

然后

variant['price']

但两者都返回no implicit conversion of ShopifyAPI::Variant into String

标签: ruby-on-railsrubyshopify-app

解决方案


product = ShopifyAPI::Product.find(shopify_product_id)
product.variants.map(&:price)

它会给你一系列的价格,因为产品可能有多个变体。你也可以使用.pluck方法而不是.map


推荐阅读