Search code examples
ruby-on-railsactiverecorddelayed-job

delayed_job_active_record - Undefined method `any?'


Attempting to send some stuff to the background with delayed_job_active_record, but how come I can't use any?? Works fine when things are not sent into the background.

undefined method `any?' for #<Delayed::Backend::ActiveRecord::Job:0x000000044b1348>

index.html.erb

<% if @products.any? %>
  <div class="products">
    <% @products.each do |product| %>
      <%= product.name %>
    <% end %>
  </div>
<% else %>
  <div class="products processing">

    <!-- Try again later -->

  </div>
<% end %>

main_controller.rb

class MainController < ApplicationController
  def index
    # Delay fetching
    @products = Affiliate.delay.fetch
  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

Solution

  • This doesn't work because @products isn't an array any more - it's a reference to a job that will get executed at some time in the future

    You need a rethink of how your setup works. For example your view could poll via Ajax to see if the job has been completed. If it has then fetch the results from the DB, since you seem to be saving the API results there.