Skip to content

Instantly share code, notes, and snippets.

@dt1973
Last active August 29, 2015 14:22
Show Gist options
  • Save dt1973/ecebdb2bdd36d4cd2b3a to your computer and use it in GitHub Desktop.
Save dt1973/ecebdb2bdd36d4cd2b3a to your computer and use it in GitHub Desktop.

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

NOW WORKING

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 %>
@creativereason
Copy link

Try changing this:
@products = Affiliate.fetch
to this:
@products = Affiliate.all

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment