Skip to content

Instantly share code, notes, and snippets.

@mr-dxdy
Created March 11, 2014 07:03
Show Gist options
  • Save mr-dxdy/9480871 to your computer and use it in GitHub Desktop.
Save mr-dxdy/9480871 to your computer and use it in GitHub Desktop.
How to get the current_user in a model observer? Solution!
# install devise
# rails generate devise user
# rails g scaffold task name:string description:text
class ApplicationController < ActionController::Base
before_filter :authenticate_user!
around_filter :set_current_user_for_thread
protect_from_forgery
protected
def set_current_user_for_thread
Thread.current[:current_user] = current_user
begin
yield
ensure
Thread.current[:current_user] = nil
end
end
end
class BaseObserver < ActiveRecord::Observer
def current_user
Thread.current[:current_user]
end
end
class TaskObserver < BaseObserver
def after_create(task)
puts "#{current_user.email} created #{task.name}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment