Created
March 11, 2014 07:03
-
-
Save mr-dxdy/9480871 to your computer and use it in GitHub Desktop.
How to get the current_user in a model observer? Solution!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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