Search code examples
ruby-on-railsdevise

how to access rails helper method current_user inside rails job?


I have the following code inside a Rails job:

class MessageBroadcastJob < ApplicationJob
  queue_as :default

  def perform(message)
   ActionCable.server.broadcast "room_channel", message: render_message(message),msg: message, user: current_user
  end

  private
  def render_message(message)
    ApplicationController.renderer.render(partial: 'messages/message', locals: { message: message})
   end
end

As you can see, I want to pass current_user, but I can't access the devise Rails helper method.


Solution

  • Devise helper methods are not available in ActiveJobs, what you can do instead is pass the current_user id to the perform method, and fetch the user there e.g.

    def perform(message, current_user_id)
      current_user = User.find(current_user_id)
      ActionCable.server.broadcast "room_channel", message: render_message(message),msg: message, user: current_user
    end