user2814321 user2814321 - 2 months ago 28
Ruby Question

How to create product with default variant data using Shopify_api gem

I'm getting started with the shopify api ruby gem and just about to create products atm, but I'm already stuck at something very basic ... being that I can't create a (none-variant) product if I want to send my price and inventory data along.

If I'm correct, a product without variants actually has a 'Default Title' variant with the sku, price, inventory etc. But I can't figure out the correct way to do this ... This is what I have now:

new_product = ShopifyAPI::Product.new
new_product.title = "Burton Custom Freestlye 151"
new_product.product_type = "Snowboard"
new_product.vendor = "Burton"
new_product.published = "false"
new_product.save

new_product.variants << ShopifyAPI::Variant.new(
:option1 => "Default Title",
:price => 12.95,
:inventory_management => "shopify",
:inventory_quantity => 10
)
new_product.save


But this results in a product without any of the default variant data.

Tried several things but I'm not getting anywhere closer (like this one: http://stackoverflow.com/a/12857132/2814321, also not working) ... And the shopify docs aren't really helpful either.

But I'm sure any of you guys can help me with this noobish problem ... right?

Answer

Been able to solve it this way:

  variant = new_product.variants
  variant[0].price = $price
  variant[0].sku = $sku
  variant[0].weight = $g
  variant[0].weight_unit = "g"
  variant[0].inventory_quantity = $qty
  variant[0].inventory_management = "shopify"
  new_product.save

I guess – correct me if I'm wrong – this does work because the default variant is already existing, hence I have to access it (variant[0]), whereas in my question code I was trying to create a new one.

Comments