Search code examples
ruby-on-railsresque

Resque job undefined method 'current_user'


It's my first attempt at Resque and doing background jobs, and I'm kind of stuck.

I have two issues at hand.

  1. It gives me the error

    undefined local variable or method `current_user'
    
  2. I am not sure if what I am pushing to the worker is indeed the most correct thing.

Here is my code:

schedules_controller.rb

  def trial
@schedule = current_user.schedules.new
if @schedule.save
  user = User.find(params[:id])
  @client = Buffer::Client.new(user.token)
  Resque.enqueue(ScheduleTweets, @client)
  @schedule.update_attribute(:trial, true)
  flash[:notice] = "success"
  redirect_to :back
else 
  flash[:alert] = "Try again."
  redirect_to :back
end

end

and the worker:

apps/workers/schedule_tweets.rb

class ScheduleTweets
 @queue = :schedules_queue

 def self.perform(client)
  user = User.find(params[:id])
  client = Buffer::Client.new(user.token)
  @list = List.first(6)
  @profiles = client.profiles
  @profile_ids = profiles.map(&:id)
  @list.each do |list|
    client.create_update(body: {text: "#{list.text}", profile_ids: @profile_ids })
  end
 end
end 

end

my thought process is that the client is the core of the entire process and should thus be the one. However @profile_ids also contains anywhere from 1-5 values.

When I run the task I get the undefined local variable or method 'current_user'. How do I fix that, also am I doing it right by choosing the @client as the thing to add?


Solution

  • Try this schedules_controller.rb

    def trial
      @schedule = current_user.schedules.new
      if @schedule.save
        user = User.find(params[:id])
        @client = Buffer::Client.new(user.token)
        Resque.enqueue(ScheduleTweets, user.id)
        @schedule.update_attribute(:trial, true)
        flash[:notice] = "success"
        redirect_to :back
      else
        flash[:alert] = "Try again."
        redirect_to :back
      end
    end
    

    and the worker:

    apps/workers/schedule_tweets.rb

    class ScheduleTweets
      @queue = :schedules_queue
    
      def self.perform(user_id)
        user = User.find(user_id)
        client = Buffer::Client.new(user.token)
        @list = List.first(6)
        @profiles = client.profiles
        @profile_ids = @profiles.map(&:id)
        @list.each do |list|
          client.create_update(body: {text: "#{list.text}", profile_ids: @profile_ids })
        end
      end
    end