Rails: How to iterate over products from hash? (Amazon API / Vacuum)

人盡茶涼 提交于 2019-12-23 04:07:09

问题


Expanding on Rails: How to extract values from hash? (Amazon API / Vacuum) -- how do I make these newly dug up values available to my views?

Currently getting:

undefined method `image_url' for #<Hash:0x848402e0>

Extracted source (around line #5):
<%= link_to image_tag(product.image_url), product.url %> 

main_controller.rb:

class MainController < ApplicationController
  def index
    request = Vacuum.new('GB')

    request.configure(
      aws_access_key_id: 'ABCDEFGHIJKLMNOPQRST',
      aws_secret_access_key: '<long messy key>',
      associate_tag: 'lipsum-20'
    )

    params = {
      'SearchIndex' => 'Books',
      'Keywords'=> 'Ruby on Rails',
      'ResponseGroup' => "ItemAttributes,Images"
    }

    raw_products = request.item_search(query: params)
    hashed_products = raw_products.to_h

    # puts hashed_products['ItemSearchResponse']['Items']['Item'].collect{ |i| i['ItemAttributes']['Title'] }
    # puts hashed_products['ItemSearchResponse']['Items']['Item'].collect{ |i| i['DetailPageURL'] }
    # puts hashed_products['ItemSearchResponse']['Items']['Item'].collect{ |i| i['LargeImage']['URL'] }

    @products = []

    @products = hashed_products['ItemSearchResponse']['Items']['Item'].each do |item|
      product = OpenStruct.new
      product.name = item['ItemAttributes']['Title']
      product.url = item['DetailPageURL']
      product.image_url = item['LargeImage']['URL']

      @products << product 
    end
  end
end

index.html.erb:

<h1>Products from Amazon Product Advertising API</h1>
<% if @products.any? %>
  <% @products.each do |product| %>
    <div class="product">
      <%= link_to image_tag(product.image_url), product.url %>
      <%= link_to product.name, product.url %>
    </div>
  <% end %>
<% end %>

回答1:


I wouldn't turn the entire Amazon hash into an OpenStruct. And since product.name is nil you can't do a find on it.

Instead, just loop through the Amazon items, assign them to your product, and then add to the @products array:

@products = []
hashed_products['ItemSearchResponse']['Items']['Item'].each do |item|
  product = OpenStruct.new
  product.name = item['ItemAttributes']['Title']
  @products << product 
end


来源:https://stackoverflow.com/questions/23417307/rails-how-to-iterate-over-products-from-hash-amazon-api-vacuum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!