0

I need to save all controller notification to database. I create a /config/initializers/notifications.rb

ActiveSupport::Notifications.subscribe('process_action.action_controller') do |name, start, finish, id, payload|
  Action.create(
    action_type: name,
    user: current_user,
    data: payload
  )
end

but I get error:

undefined local variable or method `current_user' for main:Object

current_user is a helper it app/helpers/session_helper.rb and it works in entire application.

I need to know user, which made action. How can I call current_user in this context?

vovan
  • 1,460
  • 12
  • 22

3 Answers3

0

current_user is usually set in the application_controller of your application. If you use a gem like Devise to handle user authentications for example, they take care of setting such method for you.

The initializers' code is executed when you launch your application on your server (local machine or remote server), therefor you understand that a "current_user" (understand a "logged in" user) simply does not exists (yet).

Source - is it possible for current_user to be initializer, in rails 3?

Hope this helps!

Community
  • 1
  • 1
Rajdeep Singh
  • 17,621
  • 6
  • 53
  • 78
  • O! really, I define `current_user` in `ApplicationController` `class ApplicationController < ActionController::Base ... include SessionsHelper ...` – vovan Jul 17 '15 at 07:22
0

current_user is a helper it app/helpers/session_helper.rb and it works in entire application.

Let me correct you here.

You can't access current_user in your initializer files. Initializers are run once on application startup, so don't expect accessing current_user like this.

RAJ
  • 9,697
  • 1
  • 33
  • 63
0

I found solution: append_info_to_payload

class ApplicationController < ActionController::Base
  ...
  def append_info_to_payload(payload)
    super
    payload[:current_user] = current_user
  end

From this answer: How to add attribute to existing Notifications payload?

Community
  • 1
  • 1
vovan
  • 1,460
  • 12
  • 22