Question

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 %>
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top