Save items fetched via REST Client to database
Live app which you can run on the fly: http://runnable.com/VXH_qU3Kk_F-ndtP/rest-client-test
app/controllers/main_controller.rb
class MainController < ApplicationController
def index
@products = Affiliate.all
end
end
app/models/affiliate.rb
require "rest_client"
class Affiliate < ActiveRecord::Base
def self.fetch
response = RestClient::Request.execute(
:method => :get,
:url => "http://api.shopstyle.com/api/v2/products?pid=uid7849-6112293-28&fts=women&offset=0&limit=10"
)
@products = JSON.parse(response)["products"].map do |product|
product = OpenStruct.new(product)
affiliate = Affiliate.find_or_create_by(:name => product.name, :url => product.url)
affiliate.save
end
end
end
20150604213141_add_items_to_affiliates.rb
class AddItemsToAffiliates < ActiveRecord::Migration
def self.up
change_table(:affiliates) do |t|
t.string :name
t.string :url
end
end
end
index.html.erb
<h1>Items from affiliate API</h1>
<% if @products.any? %>
<% @products.last(10).each do |product| %>
<div class="product">
<%= link_to product.name, product.url %>
</div>
<% end %>
<% end %>
Try changing this:
@products = Affiliate.fetch
to this:
@products = Affiliate.all