目前在后台(REST Client)从此外部API获取一些项目(DelayedJob),然后将它们保存到数据库中。计划是使用Rails路由检查项目是否已保存到数据库,即。什么时候开始通过Ajax拉入它们是安全的。
但我的check_items_loaded
路线出了什么问题?我以为它应该寻找url
,而不是id
?
Started GET "/check_items_loaded" 2015-06-06 00:43:03 +0000
Processing by MainController#check_items_loaded as */*
Affiliate Load (0.4ms) SELECT "affiliates".* FROM "affiliates" WHERE "affiliates"."id" = ? LIMIT 1 [["id", nil]]
Completed 404 Not Found in 52ms
ActiveRecord::RecordNotFound (Couldn't find Affiliate with 'id'=):
app/controllers/main_controller.rb:8:in `check_items_loaded'
您可以即时投放的实时应用:http://runnable.com/VXIdQ6KuRrYPdhKs/rest-client-ajax
的routes.rb
get '/check_items_loaded', to: 'main#check_items_loaded', as: :check_items_loaded
main_controller.rb
class MainController < ApplicationController
def index
# Delay fetching
@products = Affiliate.delay.fetch
end
def check_items_loaded
@items_status = Affiliate.find(params[:url])
respond_to do |wants|
wants.js
end
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)
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
答案 0 :(得分:2)
当您运行#find(foo)
时,无论如何,ActiveRecord都会将foo
中存储的值视为id列。为了搜索匹配的url参数,您实际需要的是Affiliate.find(params[:url])
而不是Affiliate.where(url: params[:url])
。