Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1devise

Undefined local variable or method `current_user' for Observer?


I've looked at a couple of questions about using current_user for an Observer and tried to implement what one said but its not working (see here).

I'm trying to create an engineer by my observer when the checkbox is marked true. An engineer and army belong to a user:

models/user.rb

class User < ActiveRecord::Base
  cattr_accessor :current 
  has_many :armies
  has_many :engineers
end

controllers/application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :set_time_zone, :set_current_user

  private

  def set_current_user
    User.current = current_user
  end
end

models/army_observer.rb

class ArmyObserver < ActiveRecord::Observer
  def after_save(army)
    if army.siege
      Engineer.create({ :user_id => current_user.id, :army_id => :army_id })
    end
  end
end

With this code it gives me the error:

undefined local variable or method `current_user' for #<ArmyObserver:0x4e68970>

Any other way? Maybe its conflicting with the Devise current_user method? Maybe Its better to keep the current_user in the controller? If so how would I do that?

Thanks just a newbie learning still.


Solution

  • You're assigning Devise's current_user to the User.current class accessor precisely because it is not available on the model (and observer) level. So instead of trying to use current_user there, use the class accessor you just created:

    Engineer.create({ :user_id => User.current.id, :army_id => :army_id })
    

    EDIT:

    BTW, I don't think this is thread safe - unless you also implement the first part of this solution linked in one of the answers to the post you referenced.