Create and retrieve metafields for shop resource

Create and retrieve metafields for shop resource

Navin2
Shopify Partner
34 0 6

Hi guys,

I am trying to create a metafield with value for shop resource and also retrieve the same in ROR using ShopifyAPI gem.

Here is the code that i am trying:

post_data = params[:post_data]

result = ShopifyAPI::Metafield.new({
            :description => 'Global priority by Xsell App',
            :namespace => 'global',
            :key => 'priority',
            :value => post_data,
            :value_type => 'string'
        })

Also retrieving code is as below:

meta = ShopifyAPI::Metafield.find(:all,:params=>{:namespace => "global", :key => "priority"})
  		if meta.present?
  		@metafield = meta.value
  		end

But I gues this is not working as i cannot retrieve the data saved from above code. However when trigger the save action with above code it returns success.

Is there anything that I am doing wrong here? Or is there any other way to do it?

Thanks in advance!!

Regards,

Navin

 

Replies 3 (3)

KieranMasterton
Shopify Staff (Retired)
22 0 4

Hey Navin!

It looks like you need to associate the metafield with the shop resource. First you need to create the metafield and then add that to your resource, in this case the shop. The example below should help I think:

shop = ShopifyAPI::Shop.current
metafield = ShopifyAPI::Metafield.new(key: "priority", namespace: "global", value: "high", value_type: "string")
shop.add_metafield(metafield)
@metafield_value = ShopifyAPI::Metafield.find(:first,:params=>{:resource => "shop", :namespace => "global", :key => "priority"}).value

I hope this helps!

To learn more visit the Shopify Help Center or the Community Blog.

nouredin
New Member
4 0 0

I have a question related to this point.

Which scope does my app need to have in order to add/update shop metafields?

 

Thanks

Navin2
Shopify Partner
34 0 6

Thanks Kieran,

You saved my day!! I was going to try HTTParty gem and try it another way, but it is quick.

I didn't find anything regarding this over the internet. I will surely write on this, so that other can easily find the solution.

Thank you again!! 

Regards,

Navin