【问题标题】:Shopify API Variant not being returned with product_id attributeShopify API 变体未与 product_id 属性一起返回
【发布时间】:2013-05-14 04:05:30
【问题描述】:

所以我使用 Shopify Gem 访问 Shopify API,并注意到 product_id 属性没有在简单的 ShopifyAPI::Variant.find 调用的响应正文中返回。

1.9.3p194> ShopifyAPI::Variant.find(209901733)
 => #<ShopifyAPI::Variant:0x007fbf7225d3f0 @attributes={"barcode"=>nil, "compare_at_price"=>"198.00", "created_at"=>"2012-03-23T14:11:39+11:00", "fulfillment_service"=>"manual", "grams"=>1000, "id"=>209901733, "inventory_management"=>"shopify", "inventory_policy"=>"deny", "option1"=>"38", "option2"=>"Ivory Mini Twill", "option3"=>nil, "position"=>16, "price"=>"198.00", "requires_shipping"=>true, "sku"=>"3063", "taxable"=>true, "title"=>"38 / Ivory Mini Twill", "updated_at"=>"2013-04-24T10:25:27+10:00", "inventory_quantity"=>2}, @prefix_options={}, @persisted=true> 

根据here发布的新文档,应该返回product_id字段。

GET /admin/variants/#{id}.json
Hide Response
HTTP/1.1 200 OK

{
  "variant": {
    "barcode": "1234_pink",
    "compare_at_price": null,
    "created_at": "2013-05-01T15:35:21-04:00",
    "fulfillment_service": "manual",
    "grams": 200,
    "id": 808950810,
    "inventory_management": "shopify",
    "inventory_policy": "continue",
    "option1": "Pink",
    "option2": null,
    "option3": null,
    "position": 1,
    "price": "199.00",
    "product_id": 632910392,
    "requires_shipping": true,
    "sku": "IPOD2008PINK",
    "taxable": true,
    "title": "Pink",
    "updated_at": "2013-05-01T15:35:21-04:00",
    "inventory_quantity": 10
  }
}

【问题讨论】:

    标签: ruby-on-rails shopify


    【解决方案1】:

    它在 json 中,但不在从 json 创建的 ActiveResource 中。原因是Variant activeresource中的这段代码:

        self.prefix = "/admin/products/:product_id/"
    
        def self.prefix(options={})
          options[:product_id].nil? ? "/admin/" : "/admin/products/#{options[:product_id]}/"
        end
    

    如果您愿意,您可以创建自己的类来获取单例变体:

          module ShopifyAPI
            class VariantWithProduct < Base
              self.prefix = "/admin/"
              self.element_name = "variant"
              self.collection_name = "variants"
            end
          end
    

    并使用此类通过 id 获取单个变体:

        ShopifyAPI::VariantWithProduct.find(xxxxxx)
    

    【讨论】:

    • 谢谢朋友,我检查了 JSON 并做了和你一样的观察。它只是需要更新的 A/R 类。
    【解决方案2】:

    Michael 对问题的诊断是正确的。对我来说,解决这个问题的最简单方法是获取产品资源而不是变体。 ShopifyAPI::Product ActiveResource 对象确实包含变体。

    product = ShopifyAPI::Product.find(product_id)
    variant = product.variants.find { |v| v.id == variant_id }
    

    【讨论】:

    • 这种方法的问题是产品对象被直接调用而不是变体。这意味着我需要进行更多的数据库调用来解决关联问题。感谢您抽出宝贵时间。
    • 在此 API 调用之后,您在 ActiveResource 对象中同时拥有产品 变体信息。从这里查找变体数据不是数据库查询,只是通过(小)数组进行搜索。这是您在问题中寻找的所有数据,因此我认为它不应转化为比您预期更多的数据库查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多