Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a specific metafield for a product using Shopify API, Ruby on Rails

In liquid templates this is achieved like so:

{{ product.metafields.book.author }}

Which returns the value of 'author' for it's key 'book'

I'm using Shopify API and Ruby on Rails and have successfully looped over each metafield for a given product:

In the controller:

@products = ShopifyAPI::Product.find(:all, :params => {:limit => 10})

In the view:

<% @products.metafields.each do |metafield| %>
<%= metafield.key %> : <%= metafield.value %>
<% end %>

This returns all of the metafields for a product, as expected. How do I return only those metafields matching a specific key i.e. 'book' from the example above?

like image 926
user1137277 Avatar asked Jul 18 '12 09:07

user1137277


People also ask

How do I get Metafield values in Shopify?

From your Shopify admin, go to the part of your store where you want to add a Metafield value. For example, a specific product, collection, or customer. Click on the rating metafield, and then enter a value. Click Save.


1 Answers

# add metafield
product = ShopifyAPI::Product.find(product_id)
product.add_metafield(ShopifyAPI::Metafield.new({
   :description => 'Author of book',
   :namespace => 'book',
   :key => 'author',
   :value => 'Kurt Vonnegut',
   :value_type => 'string'
}))

# retrieve metafield
author = ShopifyAPI::Metafield.find(:first,:params=>{:resource => "products", :resource_id => product.id, :namespace => "book", :key => "author"}).value

More info: http://www.shopify.com/technology/3032322-new-feature-metafields

like image 58
Paul Mason Avatar answered Oct 01 '22 18:10

Paul Mason