Search code examples
ruby-on-railsrubyresqueresque-scheduler

Resque Worker: Objects and methods not available in worker


I have the following worker in my web app

class TweetSender
    @queue = :tweets_queue 

        def self.perform(tweet_id)
            message = Tweet.where(:status_id => 0).order(:created_at, :id).limit(1)
            message.update_attribute(status_id = 1)
            $client.update(message.text)

        end
end

It gets schedueled by the following resque-scheduler tweet_scheduler.yml

tweet_sender:

  cron: "0 20 * * * Europe/Stockholm"
  class: "TweetSender"
  queue: tweets_queue
  args: tweet_id
  description: "This job sends daily tweets from the content db"

Which gets defined by he resque.rake

require 'resque/tasks'
require 'resque/scheduler/tasks'
task 'resque:setup' => :environment

namespace :resque do
  task :setup do
    require 'resque'


  end

  task :setup_schedule => :setup do
    require 'resque-scheduler'
    Resque.schedule = YAML.load_file('tweet_schedule.yml')
    require 'jobs'
end
task :scheduler => :setup_schedule
end

In the resque web interface I get the following error

Exception
NoMethodError
Error
undefined method `update_attribute' for #<Tweet::ActiveRecord_Relation:0x839ca814>
/home/jan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.0/lib/active_record/relation/delegation.rb:136:in `method_missing'
/home/jan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.0/lib/active_record/relation/delegation.rb:99:in `method_missing'
/home/jan/Documents/social/app/jobs/tweet_sender.rb:6:in `perform'

I alos tried implementing the tweet_sender.rb without the update_atttribute methods like so:

class TweetSender
    @queue = :tweets_queue 

        def self.perform(tweet_id)
            message = Tweet.where(:status_id => 0).order(:created_at, :id).limit(1)
            message.status_id = 1
            message.save
            $client.update(message.text)

        end
end

And the get the following error:

Exception
NoMethodError
Error
undefined method `status_id=' for #<Tweet::ActiveRecord_Relation:0x83195bf8>
/home/jan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.0/lib/active_record/relation/delegation.rb:136:in `method_missing'
/home/jan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.0/lib/active_record/relation/delegation.rb:99:in `method_missing'
/home/jan/Documents/social/app/jobs/tweet_sender.rb:6:in `perform'

Why are my methods and the standard rails emthods no available in my worker? Do I need to explicitly require them somewhere?


Solution

  • limit returns an instance of ActiveRecord::Relation.

    What you really want to get is an instance of Tweet model.

    Use first:

    message = Tweet.where(status_id: 0).order(:created_at, :id).first