我試圖使用REST Client和DelayedJob加載從這個外部API的一些項目。REST客戶端回調:如何分辨當項目完成加載?
但是,與Ajax check for database change using route不同,這些項目不會保存到數據庫,而是直接進入視圖 - 那麼如何知道它們何時完成加載,以便我可以使用Ajax將它們加載到客戶端中?
現場應用程序,它可以在飛行運行:http://runnable.com/VW9rQx-KiIFfmpII/ajax-affiliates
應用程序/控制器/ main_controller.rb
class MainController < ApplicationController
def index
# Delay fetching
@products = Affiliate.delay.fetch
end
# Pseudo-code from SO `ajax-check-for-database-change-using-route`
#
# def check_items_loaded
# @items_status = Affiliate.find(params[:id]).items_loaded
# respond_to do |wants|
# wants.js
# end
# end
end
的config/routes.rb中
# Pseudo-code from SO `ajax-check-for-database-change-using-route`
# get '/check_items_loaded/:id', to: 'photos#check_items_loaded', as: :check_items_loaded
應用程序/模型/ affiliate.rb
require "rest_client"
module Affiliate
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
end
# More pseudo-code
# Add `items_loaded` boolean to database?
# private
# def set_items_loaded
# self.update_attributes(items_loaded: ???)
# end
end
看起來不錯,謝謝你,但有沒有辦法,我可以做到這一點,而無需涉及第三方服務? –