将从API获取的项目保存到数据库中

时间:2015-06-04 21:56:08

标签: ruby-on-rails

目前在后台(REST Client)从此外部API获取10个项目(DelayedJob)。但是如何在加载完成后将它们保存到数据库中?

main_controller.rb

class MainController < ApplicationController
  def index
    # Delay fetching
    @products = Affiliate.delay.fetch
  end
end

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)
      product
    end

    # CODE TO INSERT INTO DB GOES HERE?
    # THIS MAYBE? @products.save!
  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

1 个答案:

答案 0 :(得分:1)

您的问题有点困惑,但如果您要问如何将数据从product映射到affiliate,我们需要了解有关数据的更多信息。 ......

但一般来说,在Rails数据中保存属性只是:

model_instance = Model.new #or model = Model.find(id) #or model = Model.where("conditions")
model_instance.attribute_name = new_attribute_value
mdoel_instance.save

因此,在您的情况下,您可以通过将products循环中的数据映射到affiliate来查找或创建新的联盟会员。

这样的事情:

products = JSON.parse(response)["products"].map do |product|
  product = OpenStruct.new(product)
  affiliate = Affiliate.find_or_create_by_name_and_url(:name => product.name, :url => product.url)
  #or
  affiliate = Affiliate.new #or Affiliate.create(:name => product.name, :url => product.url)
  affiliate.save
end 

处理active_record搜索/更新的方法有很多种。 The guide is a good resource for the basics