How to filter product metafields by key using Ruby on Rails with Shopify API

I’m working with the Shopify API in my Rails app and need help filtering metafields by a specific key.

In Liquid templates, you can access a particular metafield like this:

{{ product.metafields.category.title }}

This gets the ‘title’ value from the ‘category’ namespace.

Currently in my Rails application, I can fetch all metafields successfully:

Controller code:

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

View code:

<% @items.metafields.each do |field| %>
  <%= field.key %> => <%= field.value %>
<% end %>

This displays every metafield for each product. But I only want to show metafields that have a particular key, like ‘category’ from my example. What’s the best way to filter the metafields collection to return only the ones matching my target key?

Skip the view filtering - do it when you fetch from the API instead. Add metafield params to your controller like this: @items = ShopifyAPI::Product.find(:all, :params => {:limit => 5, :fields => 'id,title,metafields'}) then grab specific metafields with product.metafields.find { |m| m.namespace == 'category' && m.key == 'title' }. Less data transfer and cleaner views. Way more efficient when you’ve got products with tons of metafields - you’re not loading stuff you don’t need.

The other responses work, but I’d use the where method for larger metafield collections. Try @items.each { |product| filtered_fields = product.metafields.where(key: 'category') } - it performs way better than select with ActiveRecord collections. I hit memory issues on a project where products had 20+ metafields each. Switching from select to where cut load times significantly. You can also chain conditions for namespace and key filtering: product.metafields.where(namespace: 'custom', key: 'category') works great for specific filtering.

just add a condition in your view loop like <% @items.metafields.select { |field| field.key == 'category' }.each do |field| %> - filters before looping through them. works great when I only need specific metafield keys

You could also use find_by - it returns nil instead of throwing errors when nothing matches. Try field = product.metafields.find_by(key: 'category') then check if field exists before displaying it. Prevents crashes when some products don’t have that metafield.