Flynt Hamlock
Flynt Hamlock

Reputation: 359

Unable to update attribute - undefined method

Missing something fundamental here. Unable to update items_loaded once REST Client is done fetching some items from this API.

Live app which you can run on the fly: 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

Upvotes: 0

Views: 86

Answers (1)

XavM
XavM

Reputation: 873

Actually, in your class Affiliate, you defined the method self.set_items_loaded which get all Affiliate object and set attribute items_loaded to true on each object of this class.

If you really want to do that, you should write that

affiliate.rb

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

main_controller.rb

Affiliate.set_items_loaded

If you just want to update one object of Affiliate to set item_loaded to true, you should define your method that way and use it on one object

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

Upvotes: 1

Related Questions