Search code examples
ruby-on-rails-4observers

Observe primary application models from within Rails engine observer


I have a Rails engine that has no models of its own; just controllers, views, and observers that add functionality to the primary application.

I'm attempting to create an observer but can not get Rails to notice it's existence -- the after_create actions and debug statements in the observer are ignored and inserting syntax errors into the file does not raise an error on startup or when insert a row in the observed table.

I've tried all of the techniques mentioned here with no effect.

#/engines/loansengine/lib/loansengine/engine.rb
module Loansengine
  class Engine < ::Rails::Engine
    isolate_namespace Loansengine

    # OBSERVERS
    config.active_record.observers = ['Loansengine::TourObserver']
  end
end

Observer:

#/engines/loansengine/observers/loansengine/tour_observer.rb
class Loansengine::TourObserver  < ActiveRecord::Observer
  observe :tours

  def after_create(tour)
    test_observer(tour)
  end

  private

  def test_observer(tour)
    tour.agent_comments = 'pink'
    tour.save
  end

end

Solution

  • Think I've figured this out:

    module Loansengine
      class Engine < ::Rails::Engine
        isolate_namespace Loansengine
    
        config.before_initialize do
          config.active_record.observers << 'Loansengine::TourObserver'
        end
      end
    end