【问题标题】:Delayed_job does nothing : TypeError: can't convert nil into StringDelayed_job 什么都不做:TypeError: can't convert nil into String
【发布时间】:2013-07-31 17:20:48
【问题描述】:

从“https://github.com/collectiveidea/delayed_job”关注delayed_job。我可以知道为什么我的延迟工作什么都不做吗?我运行“rake jobs:work”广告时遇到了这些错误

错误:

Company#update_count_without_delay failed with TypeError: can't convert nil into String - 2 failed attempts

完成:

  1. 在 gemfile 中添加了“gem 'delayed_job_active_record'”
  2. 在控制台中:“rails generate delayed_job:active_record”
  3. 在控制台中:“rake db:migrate”

我遵循了这个指示:

If a method should always be run in the background, you can call #handle_asynchronously after the method declaration:

class Device
  def deliver
    # long running method
  end
  handle_asynchronously :deliver
end

device = Device.new
device.deliver

型号:

require 'json'
require 'net/http'
require 'rubygems'
require 'delayed_job'

class Company < ActiveRecord::Base
before_save :validate_fbid

scope :toplikes, order("count desc").limit(20)

attr_accessible :desc, :fbid, :name, :url, :count

url_regex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/ 


validates :name,    :presence   => true

validates :url,     :presence   => true,
                :format     => { :with => url_regex },
                :uniqueness => { :case_sensitive => false }
validates :fbid,    :presence   => true
validates :desc,    :presence   => true

def update_count
    uri = URI("http://graph.facebook.com/" + fbid)
    data = Net::HTTP.get(uri)
    self.count = JSON.parse(data)['likes']
end

handle_asynchronously :update_count     
end 

控制器:

def create 
    company = Company.new(params[:company])

    if company.save 
        @message = "New company created."
        company.update_count
        redirect_to root_path
    else 
        @message = "Company create attempt failed. Please try again."
        redirect_to new_path 
    end             
  end 
  1. 在模型顶部添加了“require 'delayed_job'”
  2. 重启我的服务器

【问题讨论】:

  • 展示你的Company类,尤其是Company#count=的实现。
  • @MarekLipka 更新了 CompanyController,我没有 Company#count。
  • 我的意思是 Company 模型,而不是控制器。
  • @MarekLipka 添加了模型类。

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 rubygems delayed-job


【解决方案1】:

您的Company#update_count 中有错误。应该是:

def update_count
  uri = URI("http://graph.facebook.com/" + fbid)
  data = Net::HTTP.get(uri)
  # here you should use your local variable that you set in previous line
  # instead of unset instance variable:
  update_attribute(:count, JSON.parse(data)['count'])
end

【讨论】:

  • 谢谢!这是一个愚蠢的错误。任务已完成,但我的 self.count 仍然为零。
  • @shoujo_sm 因为您没有在 update_count 方法中保留它。我更新了我的答案以反映这一点。
  • @shoujo_sm 有帮助吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多