Rails - 保存对DB的外部API调用

时间:2017-06-08 16:45:45

标签: ruby-on-rails json

我正在向外部源(Spree Commerce商店)进行GET调用以获取订单列表...调用工作正常但我需要将订单列表保存到我的rails应用程序的数据库中。我不知道该怎么做。

我的控制器:

def index
  # GRAB THE URL
  url = 'https://cuytest1.herokuapp.com/api/v1/orders.json?token=982fe19b763ee46bf1ea6ca6ddf70c61f2b6571c7434c22c'
  response = HTTParty.get(url)

  # PARSE THE RESPONSE
  @orders = response.parsed_response["orders"]
end

我的模特:

class Order < ApplicationRecord
  include HTTParty
end

我的观点:

<p id="notice"><%= notice %></p>

<h1>Orders</h1>

<table>
  <thead>
    <tr>
      <th>Number</th>
      <th>Total</th>
      <th>State</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @orders.each do |order| %>
      <tr>
        <td><%= order["number"] %></td>
        <td><%= order["total"] %></td>
        <td><%= order["shipment_state"] %></td>

      </tr>
    <% end %>
  </tbody>
</table>

如果有人能指出我正确的方向,将不胜感激。非常感谢!

1 个答案:

答案 0 :(得分:0)

# Create a new Orders table w/ a `details` column of JSON type
class CreateOrders < ActiveRecord::Migration
  def change
    create_table :orders do |t|
     t.json :details
    end
  end
end

# And a corresponding model
class Order < ApplicationRecord
end

# Then when you're fetching those orders:
Order.new(details: fetched_order_record)

# That might look something like this in practice:
client = Spree::Client.new(...)
orders = client.orders.parsed_response
orders.each do |order_hash|
  Order.create! details: order_hash
end

# Later when you load from the database
order = Order.first
order.details['total']