我需要访问当前 Controller 或从观察者方法中发出通知。
class SomeObserver < ActiveRecord::Observer
observe :some_model
cattr_accessor :current_controller
def after_create(record)
...
current_controller.flash[:notice] = "Some message!"
end
end
class ApplicationController < ActionController::Base
before_filter do
SomeObserver.current_controller = self
end
...
end
最佳答案
正如其他人所说,从观察者访问 Controller 在某种程度上违反了 MVC 原则。给出的答案也适合您的特定用例。
但是如果您需要更通用的解决方案,您可以尝试调整 Rails Sweepers 的工作方式。
Sweepers 是普通的观察者,但它们提供对 Controller 的访问,如果从 Controller 操作调用观察者。
这是通过同时使用清扫器作为观察者和 Controller 过滤器来实现的,这很容易实现,因为观察者是单例的(即它们包含 Singleton 模块)
简而言之,您必须这样做:
- 照常创建您的观察者。
将单例实例作为
around_filter
添加到您的 Controller :class ApplicationController < ActionController::Base around_filter MyObserver.instance #, only: [...] end
将过滤器的方法添加到您的观察者:
attr_accessor :controller def before(controller) self.controller = controller true #Don't forget this! end def after(controller) self.controller = nil end
现在您可以从观察者回调中访问 Controller 。但是,如果观察者是在 Controller 操作之外触发的,则 controller
为 nil
。
关于ruby-on-rails - rails : How to access current controller in an Observer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8141485/