无法更新属性 - 未定义的方法

时间:2015-06-04 13:21:28

标签: ruby-on-rails

在这里缺少一些基本的东西。一旦REST Client从此API获取某些项目,就无法更新items_loaded

您可以即时投放的实时应用http://runnable.com/VW9rQx-KiIFfmpII/ajax-affiliates

undefined method `items_loaded=' for #<Class:0x000000037cce20>
app/models/affiliate.rb:17:in `set_items_loaded'
app/controllers/main_controller.rb:8:in `index'

main_controller.rb

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

    # Let us know when fetching is done
    Affiliate.set_items_loaded
  end

  def check_items_loaded
    @items_status = Affiliate.items_loaded
    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)
      product
    end
  end

  def self.set_items_loaded
    self.items_loaded = true
  end
end

20150604120114_add_items_loaded_to_affiliates.rb

class AddItemsLoadedToAffiliates < ActiveRecord::Migration
  def self.up
    change_table :affiliates do |t|
      t.column :items_loaded, :boolean, default: false
    end
  end

  def self.down
    change_table :affiliates do |t|
      t.remove :items_loaded
    end
  end
end

1 个答案:

答案 0 :(得分:1)

实际上,在您的类Affiliate中,您定义了self.set_items_loaded方法,该方法获取所有Affiliate对象,并在此类的每个对象上将属性items_loaded设置为true。

如果你真的想这样做,你应该写那个

affiliate.rb

def self.set_items_loaded
  self.update_all(items_loaded: true)
end

main_controller.rb

Affiliate.set_items_loaded

如果您只想更新Affiliate的一个对象以将item_loaded设置为true,那么您应该以这种方式定义方法并在一个对象上使用它

affiliate.rb

def set_items_loaded
  self.items_loaded = true
end

main_controller.rb

Affiliate.first.set_items_loaded # to get the first object of Affiliate updated