Rails:如何访问Observer中的当前控制器?

And*_*kov 5 ruby controller ruby-on-rails observer-pattern

我需要访问当前控制器或从观察者方法中刷新通知.

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
Run Code Online (Sandbox Code Playgroud)

bil*_*aha 1

为什么在观察者中?您应该将闪光灯分配放入控制器中,原因是闪光灯是视图级别的问题。

或者

在 application_helper 文件中创建一个辅助方法来检查 flash 和显示。

def show_flash
[:notice, :error, :warning].collect do |key|
  content_tag(:div, flash[key], :id => key, :class => "flash flash_#{key}") unless   flash[key].blank?
end.join
end
Run Code Online (Sandbox Code Playgroud)

然后在你的布局中添加

<% show_flash %>
Run Code Online (Sandbox Code Playgroud)

对于通知、警告和错误类型的消息,这将检查是否设置了其中任何一个,如果设置了,则将其打印出来,如果没有设置,则不打印任何内容。

现在你可以使用

flash[:notice] = "Some message!"
Run Code Online (Sandbox Code Playgroud)