5

在液体模板中,这是这样实现的:

{{ 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 %>

正如预期的那样,这将返回产品的所有元字段。如何仅返回与上例中的特定键(即“书”)匹配的元字段?

4

5 回答 5

10
# 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

于 2012-12-31T01:32:11.580 回答
2

这似乎可以解决问题:

<% 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 %>
于 2012-07-18T10:38:00.000 回答
1

这有效:

ShopifyAPI::Metafield.find(:first,:params=>{:resource => "products", :resource_id => 94549954, :key => "book"}) 
于 2012-07-23T07:46:29.093 回答
0
ShopifyAPI::Metafield.find(:all,:params=>{:product_id => product.id, :key=> 'book'})
于 2012-07-19T02:43:31.657 回答
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"})
于 2016-12-29T01:36:02.160 回答