ruby-on-railsrubyamazon-product-apiexcon

How to map Amazon Products API to Rails?


I'm trying to fetch products from the Amazon Products API (using https://github.com/hakanensari/vacuum/) and display them in my Rails app. But how do I bring the product names and photos into my views?

Currently getting:

ActionView::Template::Error (undefined method `image' for #<Array:0x88486aec>):
    2: <% if @products.any? %>
    3:   <% @products.each do |product| %>
    4:     <div class="product">
    5:       <%= link_to image_tag(product.image.url), product.url %>
    6:       <%= link_to product.name, product.url %>
    7:     </div>
    8:   <% end %>

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'
    }

    #
    # NOT SURE WHERE TO TAKE IT FROM HERE
    #

    raw_products = request.item_search(query: params)

    @products = raw_products.to_h
    product = OpenStruct.new(@products)
  end
end

index.html.erb:

<% 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 %>

Solution

  • You are getting the error because raw_products isn't an array. AS par vacuum documentation, you will either have to convert it to hash by raw_products.to_h or You can also pass the response body into your own parser for some custom XML heavy-lifting:

    MyParser.new(raw_products.body) 
    

    So you have to first parse the the response properly before consuming it.


    You can just do following:

      @products = raw_products.to_h
      product = OpenStruct.new(@products)