I am trying to get the ‘src’ of the image of a product in Shopify with rails.
I do this in the controller:
@products = ShopifyAPI::Product.find(:all)
And the data I want to get of each product is its title and image so basically I am doing this in the view:
<% @products.each do |product| %>
<%= product.title %>
<%= product.images[0].src %>
<%= end %>
This line it’s not working: <%= product.images[0].src %> because product.images[0] returns this object: ShopifyAPI::Image:0x007fd6f4092338
Product.images:
“images”=>[#< ShopifyAPI::Image:0x007fd6f4092338
@attributes={“id”=>943579299853, “position”=>1,
“created_at”=>”2018-01-16T12:32:53-05:00”,
“updated_at”=>”2018-01-16T12:32:53-05:00”, “width”=>5384,
“height”=>3589,
“src”=>”https://cdn.shopify.com/s/files/1/2396/9643/products/playing-guitar-fretboard.jpg?v=1516123973“,
“variant_ids”=>[]}, @prefix_options={:product_id=>299776016397},
@persisted=true>]
How can I get the ‘src’ value?
Thank you.
edit::
product.images[0].attributes['src']
Works perfectly! But it will raise an error if the product doesn’t have any images attached to it so first you have to check if your product has an image (if images[0] == null)
2
Answers
Have you tried
<%= product.images[0].attributes['src'] %>
?I recommend checking out this blog for a better way to access your product images and their various attributes. They also include sample code. Good luck!