无法找到添加到数据库的项目 - 未定义的方法`find'

时间:2015-06-06 00:15:22

标签: ruby-on-rails

目前在后台(REST Client)从此外部API获取一些项目(DelayedJob),然后将它们保存到数据库中。计划是使用Rails路由检查项目是否已保存到数据库,即。什么时候开始通过Ajax将它们拉入客户端是安全的。

但是控制器中的Affiliate.find(params[:url])怎么办?

Started GET "/check_items_loaded" at 2015-06-06 00:00:24 +0000
Processing by MainController#check_items_loaded as */* 
Completed 500 Internal Server Error in 0ms

NoMethodError (undefined method `find' for Affiliate:Class): 
  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
  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

1 个答案:

答案 0 :(得分:3)

find是一种ActiveRecord方法。你已经宣布你的班级是这样的:

class Affiliate

如果您希望Affiliate拥有ActiveRecord方法,您将不得不这样做:

class Affiliate < ActiveRecord::Base