在液体模板中,这样就可以实现:
{{ product.metafields.book.author }}
它返回'author'的值,因为它的关键'book'
我正在使用Shopify API和Ruby on Rails,并且已成功遍历给定产品的每个元数据域:
在控制器中:
@products = ShopifyAPI::Product.find(:all, :params => {:limit => 10})
在视图中:
<% @products.metafields.each do |metafield| %>
<%= metafield.key %> : <%= metafield.value %>
<% end %>
这将返回产品的所有元字段,如预期的那样。如何仅返回与特定键匹配的元字段,即上述示例中的“book”?
答案 0 :(得分:7)
# 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
更多信息:http://www.shopify.com/technology/3032322-new-feature-metafields
答案 1 :(得分:1)
这似乎可以解决问题:
<% product.metafields.each do |metafield| %>
<% if metafield.key == "book" %>
<%= metafield.key %>: <%= metafield.value %><br/>
<% end %>
<% end %>
或
<% product.metafields.each do |metafield| %>
<% if metafield.key.include?("book") %>
<%= metafield.key %>: <%= metafield.value %><br/>
<% else %>
<% end %>
答案 2 :(得分:1)
ShopifyAPI::Metafield.find(:all,:params=>{:product_id => product.id, :key=> 'book'})
答案 3 :(得分:1)
这有效:
ShopifyAPI::Metafield.find(:first,:params=>{:resource => "products", :resource_id => 94549954, :key => "book"})
答案 4 :(得分:0)
您可以获取产品的所有元数据
@product = ShopifyAPI::Product.find(params[:id])
之后,你可以得到它的元场
@metafields = @product.metafields
或者,如果您只需要该产品的特定元字段
@metafield = ShopifyAPI::Product::Metafield.find(:all, where: {"product_id = ? AND metafield.key = ?", product.id, "book"})