Search code examples
ruby-on-railsruby-on-rails-4shopifyactiveresource

How to find Product Images depending on the Alt tag?


I have been able to set the Alt tag when uploading an image to a product, via an html form.

images = params[:images] || nil

if images
 images.each do |image|
      a = ShopifyAPI::Image.new
      a.prefix_options = {:product_id => params[:product_id]}
      a.metafields = [{:key => 'alt', :value => 'Cake', :value_type => "string", :namespace =>  "tags"}]
      a.attachment = Base64.encode64(image.read)
      a.filename = image.original_filename
      a.save
 end
else
.
.
.

But when it comes to retrieving the images for a product, where alt='Cake', I cannot seem to figure it out. I have tried searching the Metafields via the ShopifyAPI console, with no joy.


Would be nice if it were this easy...

a = ShopifyAPI::Image.where(alt: 'Cake', product_id: 245512249)

or better...

a = ShopifyAPI::Product.find(245512249)
b = a.images.select { |image| image.alt == 'Cake' }

or...

a = ShopifyAPI::Product.find(245512249)
a.images.each do |image|
  b << image if image.alt == 'Cake'
end

Solution

  • There is no way of recalling Product Images depending on the Alt tag; the ShopifyAPI does not allow for it.


    Saying that though, here is a trade secret...

    Just tag on the value of the Alt tag to the filename of the image.

    images = params[:images] || nil
    
    if images
     images.each do |image|
          a = ShopifyAPI::Image.new
          a.prefix_options = {:product_id => params[:product_id]}
          a.metafields = [{:key => 'alt', :value => 'Cake', :value_type => "string", :namespace =>  "tags"}]
          a.attachment = Base64.encode64(image.read)
          a.filename = 'Cake_'+image.original_filename
          a.save
     end
    else
    .
    .
    .
    

    That way, you can filter the Product Images via the string value 'Cake_' on the ':src' attribute.

    @product = ShopifyAPI::Product.find(params[:id])
    
    @product.images.each do |image|
      if image.attributes[:src].include?('Cake_')
        .
        .
        .
      end
    end
    

    Hope that helps!