【问题标题】:How can I get the image (src) of a Shopify product? (rails)如何获取 Shopify 产品的图像 (src)? (导轨)
【发布时间】:2018-07-25 08:25:37
【问题描述】:

我正在尝试使用 Rails 在 Shopify 中获取产品图像的“src”。

我在控制器中执行此操作:

   @products = ShopifyAPI::Product.find(:all)

我想获得的每个产品的数据是它的标题和图片,所以基本上我在视图中这样做:

<% @products.each do |product| %>
    <%= product.title %>
    <%= product.images[0].src %>
<%= end %>

此行不起作用: 因为 product.images[0] 返回此对象:ShopifyAPI::Image:0x007fd6f4092338

Product.images:

"图片"=>[#943579299853, "位置"=>1, "created_at"=>"2018-01-16T12:32:53-05:00", “updated_at”=>“2018-01-16T12:32:53-05:00”,“宽度”=>5384, “身高”=>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>]

我怎样才能得到'src'值?

谢谢。

编辑::

product.images[0].attributes['src'] 

完美运行!但是,如果产品没有附加任何图像,则会引发错误,因此首先您必须检查您的产品是否有图像(如果图像[0] == null)

【问题讨论】:

    标签: ruby-on-rails shopify-app


    【解决方案1】:

    你试过&lt;%= product.images[0].attributes['src'] %&gt;吗?

    【讨论】:

    • 是的,我试过了,但它会引发“ActionView::Template::Error (undefined method `attributes' for nil:NilClass):”
    • @Gyntonic 嗯?这很奇怪。所以,product.images[0] 确实返回了一个ShopifyAPI::Image 对象,但product.images[0].attributes['src']product.images[0] 实际上是一个nil:NilClass 对象。我对吗?这个想法是您访问 @attributes 变量,它是一个哈希,其中包含 'src' 键(根据您上面提供的内容),这似乎是您所需要的。
    • 哦,我刚刚发现了问题。你的答案是正确的!谢谢你。问题是我的一个产品没有图像,所以当我试图访问它时,显然它是空的。在访问它之前,我只需要做出一个妥协。 @杰里
    【解决方案2】:

    我建议您查看this blog,以更好地访问您的产品图片及其各种属性。它们还包括示例代码。祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 2023-02-26
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      相关资源
      最近更新 更多